PHP is object-oriented

In object-oriented programming (Object-oriented programming, abbreviation: OOP), an object is a whole consisting of information and a description of how it is processed, an abstraction of the real world.

In the real world, we are faced with objects, such as computers, televisions, bicycles and so on.

The main three characteristics of an object:

  • Behavior of the object: You can apply those actions to the object, turn on the light, turn off the light is the behavior.
  • Shape of an object: When applied those methods are how the object responds, color, size, and shape.
  • The object's representing: The object's display is equivalent to an ID card, distinguishing between the same behavior and state.

For example, Animal is an abstract class, we can be specific to a dog and a sheep, and dogs and sheep are specific objects, they have color properties, can write, can run and other behavioral states.

PHP is object-oriented


Object-oriented content

  • Class - defines the abstract characteristics of an object. The definition of a class contains the form of the data and the operation of the data.

  • Object - is an instance of a class.

  • Member Variables - Defines variables within a class. The value of the variable is not visible to the outside world, but can be accessed through a member function, and can be called an object's property after the class is instantiated as an object.

  • Member functions - defined inside the class and can be used to access the object's data.

  • Inheritance - Inheritance is the mechanism by which children automatically share parent data structures and methods, which is a relationship between classes. When you define and implement a class, you can build on a class that already exists, treat what the already existing class defines as your own content, and add some new content.

  • Parent Class - A class is inherited by another class and can be called a parent class, or a base class, or a super class.

  • Sub-classes - One class inherits other classes called sub-classes, also known as derived classes.

  • Polymorphism - Polymorphism refers to the same operation or function, a process that can be used on multiple types of objects and get different results. Different objects, receiving the same message can produce different results, a phenomenon known as polymorphism.

  • Overloading - Simply put, a function or method has the same name, but the argument list is not the same, so that functions or methods with different parameters of the same name are called overloaded functions or methods.

  • Abstraction - Abstraction refers to the abstraction into classes of objects with consistent data structures (attributes) and behaviors (operations). A class is such an abstraction that it reflects the importance of the application, ignoring other unrelated content. The division of any class is subjective, but must be related to the specific application.

  • Encapsulation - Encapsulation refers to binding the properties and behaviors of an object that exists in the real world and placing them in a logical unit.

  • Constructor - Primarily used to initialize an object when it is created, i.e. to assign an initial value to an object member variable, which is always used with the new operator in the statement in which the object was created.

  • Destructors - Destructors, in contrast to constructors, automatically execute destructors when an object ends its life cycle, such as when the function in which the object is located has been called. Destructors are often used to "clean up the aftermath" (e.g., when building objects with new open up a piece of memory space, should be released in the destructor before exiting).

In the following image, we created three objects from the Car class: Mercedes, Bmw, and Audi.

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

PHP is object-oriented


PHP class definition

PhP defines classes in the following syntax format:

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

The resolution is as follows:

  • The class uses the class keyword and is defined by the class name.

  • Variables and methods can be defined within a pair of braces after the class name.

  • The variable of the class is declared using var, and the variable can also initialize the value.

  • Functions define definitions similar to PHP functions, but functions can only be accessed through the class and its instantiated objects.

Instance

<?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;
  }
}
?>

The $this represents its own object.

PHP_EOL is a line break.


Create an object in PHP

After the class is created, we can use the new operator to instantiate the objects of the class:

$w3cschool = new Site;
$taobao = new Site;
$google = new Site;

In the above code we have created three objects, each of which is independent, and let's look at how to access member methods and member variables.

Call the member method

After instantiation of an object, we can use the object to call the member method, which can only manipulate the member variables of the object:

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

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

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

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

The full code is as follows:

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

/?member functions
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 ;
}
}

$w3cschool = new Site ;
$taobao = new Site ;
$google = new Site ;

// Call the member function, set the title and URL
$w3cschool -> setTitle ( "W3cschool tutorial" );
$taobao -> setTitle ( "Taobao" );
$google -> setTitle ( "Google Search" );

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

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

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

Run an instance . . .

The above code is executed and the output is:

W3Cschool教程
淘宝
Google 搜索
www.w3cschool.cn
www.taobao.com
www.google.com

PHP constructor

Constructor is a special method. Primarily used to initialize an object when it is created, that is, to assign an initial value to an object member variable, which is always used with the new operator in the statement in which the object was created.

PHP 5 allows developers to define a method as a constructor in a class, in the following syntax format:

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

In the example above, we can construct methods to initialize $url and $title variables:

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

Now we don't need to call the setTitle and setUrl methods anymore:

$youj new Site ('www.w3cschool.cn', 'W3Cschool tutorial');
$taobao new Site ('www.taobao.com', 'Taobao');
$google new Site ('www.google.com', 'Google Search');

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

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

Run an instance . . .

Destructor

In contrast to constructors, destructors are automatically executed when an object ends its life cycle, such as when the function in which the object is located has been called.

PHP 5 introduces the concept of destructors, similar to other object-oriented languages, in the following syntax format:

void __destruct ( void )

Instance

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

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

$obj = new MyDestructableClass();
?>

The above code is executed and the output is:

构造函数
销毁 MyDestructableClass

Inherited

PHP uses the keyword extends to inherit a class, and PHP does not support multi-inheritance in the following format:

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

Instance

In the Child_Site class inherited the Site class and extended functionality:

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

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

Method override

If the method inherited from the parent class does not meet the needs of the child class, you can override it, a process called override, also known as method override.

The getUrl and getTitle methods are overwritten in the instance:

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

Access control

PHP access control to properties or methods is achieved by adding the keyword public(public), protected, or private (private) earlier.

  • Public: Public class members can be accessed anywhere.
  • Protected: Protected class members can be accessed by themselves and their children and parent classes.
  • Private: Private class members can only be accessed by the class in which they are defined.

Access control of the property

Class properties must be defined as public, protected, and private. If defined with 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 of the method

Methods in a class can be defined as public, private, or protected. If these keywords are not set, 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

Interfaces allow you to specify which methods a class must implement, but you do not need to define the specifics of those methods.

Interfaces are defined by the interface keyword, just like a standard class, but all methods that are defined are empty.

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

To implement an interface, use the implements operator. A ll methods defined in the interface must be implemented in the class, or a fatal error will be reported. Classes can implement multiple interfaces, separating the names of multiple interfaces with commas.

<?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 define a value that remains constant in a class as a constant. You do not need to use the $ symbol when defining and using constants.

The value of a constant must be a constant, not a variable, class property, result of a mathematical operation, or a function call.

Since PHP 5.3.0, classes can be called dynamically with a variable. However, the value of the variable cannot be a keyword, such as self, parent, or static.

Instance

<?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 there is at least one method in it that is declared abstract, then the class must be declared abstract.

Classes defined as abstract cannot be instantiated.

Methods defined as abstract simply declare how they are called (parameters) and cannot define their specific functional implementations.

When inheriting an abstract class, the child class must define all abstract methods in the parent class; For example, if an abstract method is declared protected, the method implemented in the sub-class should be declared protected or public, not private.

<?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;
?>

The above code is executed and the output is:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

In addition, child class methods can contain optional parameters that do not exist in the parent class abstraction method. For example, a child class defines an optional parameter that is functional if it is not in the declaration of the parent class abstract method.

<?php
abstract class AbstractClass
{
    // 我们的抽象方法仅需要定义需要的参数
    abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{

    // 我们的子类可以定义父类签名中不存在的可选参数
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>

The output is:

Mr. Pacman
Mrs. Pacwoman

Static keywords

Declaring a class property or method is static and can be accessed directly without instantiation of the class.

Static properties cannot be accessed through an object that has been instantiated by a class (but static methods can).

Because static methods do not need to pass through objects to be called, pseudo$this is not available in static methods.

Static properties cannot be accessed by objects through the --gt; operator.

Since PHP 5.3.0, classes can be called dynamically with a variable. However, the value of the variable cannot be the 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 procedure is performed and the output is:

foo
foo

Final keyword

PHP 5 has added a final keyword. I f a method in the parent class is declared final, the child class cannot override the method. If a class is declared final, it cannot be inherited.

The following code execution will report an 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 construction method

PHP does not automatically call the construction method of the parent class in the construction method of the child class. To execute the construction method of the parent class, you need to call parent::__construct in the __construct class.

<?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 procedure is performed and the output is:

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