Latest web development tutorials

PHP Object-Oriented

In object-oriented programming (English: Object-oriented programming, Abbreviation: OOP), the object is a description of the information and information processing consisting of a whole, is the real world abstraction.

Things are objects in the real world that we face, such as computers, televisions, bicycles.

Three major characteristics of the object:

  • Behavior of the object: an object that can be applied to the operation, turn on the lights, turn off the lights is behavior.
  • Form object: When applying those methods is how to respond to the object, color, size, shape.
  • Representation of the object: an object representing the equivalent of identity, specifically distinguish what is different in the same behavior and state.

For example, Animal (animal) is an abstract class, we can be specific to a sheep with a dog, and the dog with the sheep is a specific target, they have a color attribute, you can write, you can run other acts of state.


Object-oriented content

  • Class - defines the abstract characteristics of a thing.Class definition contains the form data and operations on data.

  • Objects - is an instance of the class.

  • Member variables - variables defined within the class.The external value of the variable is not visible, but can be accessed by member functions, after the class is instantiated as an object, the properties of the object can be called a variable.

  • Member function - defined inside the class can be used for data access objects.

  • Inheritance - Inheritance is a subclass of automatic sharing of data structures and methods of the parent class, which is a relationship between classes.In the definition and implementation of a class, they can come in such a basis exists already carried out, this already existing class as defined by the content of their content, and add some new content.

  • Parent class - a class inherited by other classes, the class may be called the parent class, group or class, or superclass.

  • Subclass - a class that inherits another class is called a subclass can also be called a derived class.

  • Polymorphism - Polymorphism refers to the same operation or function, the process can be applied to the multiple types of objects and get different results.Different objects, you receive the same message may produce different results, this phenomenon is called polymorphism.

  • Overload - short, it is a function or method with the same name, but the parameter list is not the same situation, such a function or method between the different parameters of the same name, each overloaded function or method is called.

  • Abstract - The abstract refers to having consistent data structure (attributes) and behavior (operations) of objects into classes.Such a class is an abstraction, it reflects the important properties associated with the application, while ignoring other unrelated content. Any class division is subjective, but must be related to the specific application.

  • Package - Package refers to the properties and behavior of an object in the real world exists to bind together and placed in a logical unit.

  • Constructor - mainly used to initialize the object when you create an object, the object is assigned an initial value of the member variable, always use the object creation statement with the new operator.

  • Destructor - destructor (destructor) and the constructor In contrast, when the object end of its life cycle (for example, where the object is a function call is completed), the system automatically performs destructor.Destructors are often used to make "clean up the aftermath of" work (for example, when you create an object with a new one opened up memory space should be used before exiting in the destructor delete release).

The following figure we create three objects Car class: Mercedes, Bmw, and Audi.

$mercedes = new Car ();
$bmw = new Car ();
$audi = new Car ();


PHP class definition

PHP custom class usually syntax is as follows:

<?php
class phpClass {
  var $var1;
  var $var2 = "constant string";
  
  function myfunc ($arg1, $arg2) {
     [..]
  }
  [..]
}
?>

Interpreted as follows:

  • After the class usingthe class keyword plus the name of the class definition.

  • A pair of braces after the name of the class can define variables and methods ({}) inside.

  • Class variables usingvar to declare variables can also be initialized values.

  • PHP function definition is similar to the definition of the function, but the function can only be accessed through the class and its instantiated objects.

Examples

<?php
class Site {
  /* 成员变量 */
  var $url;
  var $title;
  
  /* 成员函数 */
  function setUrl($par){
     $this->url = $par;
  }
  
  function getUrl(){
     echo $this->url . PHP_EOL;
  }
  
  function setTitle($par){
     $this->title = $par;
  }
  
  function getTitle(){
     echo $this->title . PHP_EOL;
  }
}
?>

$ This variable represent their objects.

PHP_EOL newline.


PHP to create objects

After the class is created, we can use thenew operator to instantiate an object of the class:

$w3big = new Site;
$taobao = new Site;
$google = new Site;

The above code we create three objects, each of the three objects are independent, then we look at how to access member methods and member variables.

Calls member method

After the object is instantiated, we can use the object to call a member method, the method of the object can only be a member of the operating member variable of the object:

// 调用成员函数,设置标题和URL
$w3big->setTitle( "本教程" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );

$w3big->setUrl( 'www.w3big.com' );
$taobao->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );

// 调用成员函数,获取标题和URL
$w3big->getTitle();
$taobao->getTitle();
$google->getTitle();

$w3big->getUrl();
$taobao->getUrl();
$google->getUrl();

The complete code is as follows:

Examples

<? php
class Site {
/* Member variables */
var $ url;
var $ title;

/ * Member function * /
function setUrl ($ par) {
$ this -> url = $ par ;
}

function getUrl () {
. echo $ this -> url PHP_EOL ;
}

function setTitle ($ par) {
$ this -> title = $ par ;
}

function getTitle () {
echo $ this -> title PHP_EOL. ;
}
}

$ w3big = new Site;
$ taobao = new Site;
$ google = new Site;

// Member function is called to set the title and URL
$ w3big -> setTitle ( "tutorial");
$ taobao -> setTitle ( "Taobao");
$ google -> setTitle ( "Google Search");

$ w3big -> setUrl ( 'www.w3big.com ');
$ taobao -> setUrl ( 'www.taobao.com ');
$ google -> setUrl ( 'www.google.com ');

// Call member function to get the title and URL
$ w3big -> getTitle ();
$ taobao -> getTitle ();
$ google -> getTitle ();

$ w3big -> getUrl ();
$ taobao -> getUrl ();
$ google -> getUrl ();
?>

Running instance »

Implementation of the above code, the output is:

本教程
淘宝
Google 搜索
www.w3big.com
www.taobao.com
www.google.com

PHP Constructor

Constructor is a special method. Mainly used to initialize the object when you create an object, the object is assigned an initial value of the member variable, always use the object creation statement with the new operator.

PHP 5 allows developers to define a method row in a class as a constructor syntax is as follows:

void __construct ([ mixed $args [, $... ]] )

In the above example, we can initialize the $ url and $ title variable via the constructor:

function __construct( $par1, $par2 ) {
   $this->url = $par1;
   $this->title = $par2;
}

Now we do not need to call the method setTitle and setUrl:

Examples

$ w3big = new Site ( 'www.w3big.com ', ' tutorial');
$ taobao = new Site ( 'www.taobao.com ', ' Taobao');
$ google = new Site ( 'www.google.com ', 'Google search');

// Call member function to get the title and URL
$ w3big-> getTitle ();
$ taobao-> getTitle ();
$ google-> getTitle ();

$ w3big-> getUrl ();
$ taobao-> getUrl ();
$ google-> getUrl ();

Running instance »

Destructor

Destructor (destructor) and the constructor In contrast, when the object end of its life cycle (for example, where the object is a function call is completed), the system automatically performs destructor.

PHP 5 introduces the concept of a destructor, which is similar to other object-oriented languages, the syntax is as follows:

void __destruct ( void )

Examples

<?php
class MyDestructableClass {
   function __construct() {
       print "构造函数\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "销毁 " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

Implementation of the above code, the output is:

构造函数
销毁 MyDestructableClass

inherit

PHPextends keyword to inherit a class, PHP does not support multiple inheritance, in the following format:

class Child extends Parent {
   // 代码部分
}

Examples

Example Child_Site class inherits the Site class, and extends the functionality:

<?php 
// 子类扩展站点类别
class Child_Site extends Site {
   var $category;

	function setCate($par){
		$this->category = $par;
	}
  
	function getCate(){
		echo $this->category . PHP_EOL;
	}
}

Method overrides

If you can not meet the needs of a subclass inherits from the parent class method, it can be rewritten, a process called overlay method (override), also known as the overriding method.

Example rewritten getUrl and getTitle methods:

function getUrl() {
   echo $this->url . PHP_EOL;
   return $this->url;
}
   
function getTitle(){
   echo $this->title . PHP_EOL;
   return $this->title;
}

Access control

PHP on the property or method of access control is achieved by adding keywords in front of the public (public), protected (protected) or private (private) to achieve.

  • public (Public): public class member can be accessed anywhere.
  • protected (protected): protected class member can be accessed by its own as well as its sub-class and the parent class.
  • private (private): private class members can only be accessed where the class definition.

Access control attributes

Class attribute must be defined as public, protected, private one. If defined with the var, it is considered public.

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // 这行能被正常执行
echo $obj->protected; // 这行会产生一个致命错误
echo $obj->private; // 这行也会产生一个致命错误
$obj->printHello(); // 输出 Public、Protected 和 Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // 可以对 public 和 protected 进行重定义,但 private 而不能
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // 这行能被正常执行
echo $obj2->private; // 未定义 private
echo $obj2->protected; // 这行会产生一个致命错误
$obj2->printHello(); // 输出 Public、Protected2 和 Undefined

?>

Access control methods

Method in class can be defined as public, private or protected. If you do not set these keywords, the method defaults to public.

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // 声明一个公有的构造函数
    public function __construct() { }

    // 声明一个公有的方法
    public function MyPublic() { }

    // 声明一个受保护的方法
    protected function MyProtected() { }

    // 声明一个私有的方法
    private function MyPrivate() { }

    // 此方法为公有
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // 这行能被正常执行
$myclass->MyProtected(); // 这行会产生一个致命错误
$myclass->MyPrivate(); // 这行会产生一个致命错误
$myclass->Foo(); // 公有,受保护,私有都可以执行


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // 此方法为公有
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // 这行会产生一个致命错误
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // 这行能被正常执行
$myclass2->Foo2(); // 公有的和受保护的都可执行,但私有的不行

class Bar 
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }
    
    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar 
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }
    
    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>

interface

Using the interface (interface), you can specify which methods a class must implement, but do not need to define the specific content of these methods.

The interface is defined bythe interface keyword, like the definition of a standard class, but which defines all the methods are empty.

All methods defined in the interface must be public, which is characteristic of the interface.

To implement an interface, use theimplements operator.The class must implement all the methods defined in an interface, or else will report a fatal error. Class can implement multiple interfaces, use commas to separate the names of multiple interfaces.

<?php

// 声明一个'iTemplate'接口
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}


// 实现接口
class Template implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

constant

You can put in the class remains the same values ​​defined as constants. In the definition and use of the time constants do not need to use the $ symbol.

The value of the constant must be a fixed value, not a variable, class attributes, math results or function call.

Since PHP 5.3.0 onwards, you can use a variable to dynamically call the class. But the value of the variable can not be a keyword (eg self, parent or static).

Examples

<?php
class MyClass
{
    const constant = '常量值';

    function showConstant() {
        echo  self::constant . PHP_EOL;
    }
}

echo MyClass::constant . PHP_EOL;

$classname = "MyClass";
echo $classname::constant . PHP_EOL; // 自 5.3.0 起

$class = new MyClass();
$class->showConstant();

echo $class::constant . PHP_EOL; // 自 PHP 5.3.0 起
?>

Abstract class

Any class, if it contains at least one method is declared abstract, then this class must be declared as abstract.

Is defined as an abstract class can not be instantiated.

Is defined as an abstract method only declares its invocation (parameters), you can not define the specific function implementation.

Inherit an abstract class, subclass must all abstract parent class method definitions; In addition, access to these methods of control and the parent class must be the same as (or more relaxed). For example, an abstract method is declared protected, then the method implemented in the subclass should be declared as protected or public, but can not be defined as private. Also called by method must match, that is the type and number of required parameters must be consistent. For example, a subclass defines an optional parameter, and the declaration of the parent class abstract method there is no, then there is no conflict between the two statements.

<?php
abstract class AbstractClass
{
 // 强制要求子类定义这些方法
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // 普通方法(非抽象方法)
    public function printOut() {
        print $this->getValue() . PHP_EOL;
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') . PHP_EOL;

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') . PHP_EOL;
?>

Implementation of the above code, the output is:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Static Keyword

Declare class properties or methods as static (Static), you can not instantiate the class and direct access.

Static property through a class can not be instantiated object to access (but static method can).

Because static methods are not required to call through the object, the pseudo-variable $ this is not available in a static method.

To access the> operator - Static Property not by the subject.

Since PHP 5.3.0 onwards, you can use a variable to dynamically call the class. But the value of the variable can not be a keyword self, parent or static.

<?php
class Foo {
  public static $my_static = 'foo';
  
  public function staticValue() {
     return self::$my_static;
  }
}

print Foo::$my_static . PHP_EOL;
$foo = new Foo();

print $foo->staticValue() . PHP_EOL;
?>	

The above program, the output is:

foo
foo

Final Keyword

PHP 5 adds a final keyword. If the parent class method is declared final, the subclass can not override this method. If a class is declared final, it can not be inherited.

The following code execution error:

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called" . PHP_EOL;
   }
   
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called"  . PHP_EOL;
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called"  . PHP_EOL;
   }
}
// 报错信息 Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Call the parent class constructor

PHP does not automatically call the constructor of the parent class constructor in subclass. To execute the parent class constructor, we need to call theparent in the constructor of the subclass :: __ construct ().

<?php
class BaseClass {
   function __construct() {
       print "BaseClass 类中构造方法" . PHP_EOL;
   }
}
class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();  // 子类构造方法不能自动调用父类的构造方法
       print "SubClass 类中构造方法" . PHP_EOL;
   }
}
class OtherSubClass extends BaseClass {
    // 继承 BaseClass 的构造方法
}

// 调用 BaseClass 构造方法
$obj = new BaseClass();

// 调用 BaseClass、SubClass 构造方法
$obj = new SubClass();

// 调用 BaseClass 构造方法
$obj = new OtherSubClass();
?>

The above program, the output is:

BaseClass 类中构造方法
BaseClass 类中构造方法
SubClass 类中构造方法
BaseClass 类中构造方法