PHP complete se...login
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP object-oriented


What is PHP object-oriented?

In object-oriented programming (English: Object-oriented programming, abbreviation: OOP), An object is a whole composed of information and a description of how to process the information. It is an abstraction of the real world.

In the real world, the things we face are objects, such as computers, televisions, bicycles, etc.

Related learning recommendations: "PHP Object-Oriented Programming (Jade Girl Heart Sutra Edition)", "MySQLi Object-Oriented Programming Quick Introduction"

The main three characteristics of the object:

  • The behavior of the object: those operations that can be applied to the object, turning the light on and off are the behaviors.

  • The shape of the object: how the object responds, color, size, and appearance when those methods are applied.

  • Representation of objects: The representation of objects is equivalent to an ID card, specifically distinguishing the differences in the same behavior and status.

For example, Animal is an abstract class. We can specify a dog and a sheep, and dogs and sheep are concrete objects. They have color attributes and can be written , you can run and other behavioral states.

1020.png


Object-oriented content

  • Class − Defines the abstract characteristics of a thing. The definition of a class includes the form of the data and the operations on the data.

  • Object − is an instance of a class.

  • Member variables − Variables defined inside the class. The value of this variable is invisible to the outside world, but can be accessed through member functions. After the class is instantiated as an object, the variable can be called an attribute of the object.

  • Member function − Defined inside the class, it can be used to access the data of the object.

  • Inheritance − Inheritance is a mechanism for subclasses to automatically share data structures and methods of parent classes. This is a relationship between classes. When defining and implementing a class, you can do it on the basis of an existing class, take the content defined by the existing class as your own content, and add some new content.

  • Parent class − A class is inherited by other classes, and the class can be called a parent class, or base class, or super class.

  • Subclass − A class that inherits other classes is called a subclass, or it can also be called a derived class.

  • Polymorphism − Polymorphism means that the same operation, function, or process can be applied to multiple types of objects and obtain different results. Different objects can produce different results when receiving the same message. This phenomenon is called polymorphism.

  • Overloading − Simply put, it is a situation where functions or methods have the same name but different parameter lists. Such functions or methods with the same name but different parameters They call each other overloaded functions or methods.

  • Abstractness − Abstraction refers to abstracting objects with consistent data structures (attributes) and behaviors (operations) into classes. A class is an abstraction that reflects important properties related to an application while ignoring other irrelevant content. The division of any class is subjective, but must be related to the specific application.

  • Encapsulation − Encapsulation refers to binding the attributes and behaviors of an object existing in the real world together and placing them in a logical unit.

  • Constructor − Mainly used to initialize the object when creating the object, that is, assign initial values ​​to the object member variables. It is always used together with the new operator to create the object. in the statement.

  • Destructor − Destructor (destructor) is the opposite of the constructor, when the object ends its life cycle (for example, the function in which the object is located has been called) , the system automatically executes the destructor. Destructors are often used to do "clean-up" work (for example, when creating an object, use new to open up a memory space, which should be released with delete in the destructor before exiting).

In the figure below we have created three objects through the Car class: Mercedes, Bmw, and Audi.

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

1012.jpg


PHP class definition

PHP definition class usually has the following syntax format:

<?php
class phpClass {
  var $var1;
  var $var2 = "constant string";
  
  function myfunc ($arg1, $arg2) {
     [..]
  }
  [..]
}
?>
is parsed as follows:
  • Classes are defined using the class keyword followed by the class name.

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

  • class are declared using var, and variables can also be initialized.

  • Function definitions are similar to PHP function definitions, but functions can only be accessed through the class and the objects it instantiates.

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;
  }
}
?>
variable $this represents the object of itself.

PHP_EOL is the newline character.


Creating objects in PHP

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

$php = new Site;
$taobao = new Site;
$google = new Site;
In the above code, we created three objects. Each of the three objects is independent. Next, let's take a look at how to access member methods and member variables.

Call member methods

After instantiating an object, we can use the object to call member methods. The member methods of the object can only operate the member variables of the object:

Call the member function, set the title and URL

$php->setTitle( "php中文网" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );
$php->setUrl( 'www.php.cn' );
$taobao->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );
Call the member function, get the title and URL
$php->getTitle();
$taobao->getTitle();
$google->getTitle();
$php->getUrl();
$taobao->getUrl();
$google->getUrl();

Complete code As follows:

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

$php = new Site; 
$taobao = new Site; 
$google = new Site; 

// 调用成员函数,设置标题和URL 
$php->setTitle( "php中文网" ); 
$taobao->setTitle( "淘宝" ); 
$google->setTitle( "Google 搜索" ); 

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

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

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

Run Instance»

Click the "Run Instance" button to view the online instance

Execute the above code, the output result is:

php中文网
淘宝
Google 搜索
www.php.cn
www.taobao.com
www.google.com

PHP constructor

Constructor is a special method. It is mainly used to initialize the object when creating the object, that is, to assign initial values ​​to the object member variables. It is always used together with the new operator in the statement to create the object.

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

void __construct ([ mixed $args [, $... ]] )
In the above example, we can initialize through the constructor method $url and $title variables:
function __construct( $par1, $par2 ) {
   $this->url = $par1;
   $this->title = $par2;
}
Now we no longer need to call the setTitle and setUrl methods:

Example

<?php
class Site {
  /* 成员变量 */
  var $url;
  var $title;

  function __construct( $par1, $par2 ) {
    $this->url = $par1;
    $this->title = $par2;
  }
  /* 成员函数 */
  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;
  }
}

$php = new Site('www.php.cn', 'php中文网'); 
$taobao = new Site('www.taobao.com', '淘宝'); 
$google = new Site('www.google.com', 'Google 搜索'); 

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

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

Run Instance»

Click the "Run Instance" button to view the online instance


Destructor

Destructor (destructor) Contrary to the constructor, when the object ends its life cycle (for example, the function in which the object is located has been called), the system automatically executes the destructor .

PHP 5 introduced the concept of destructor, which is similar to other object-oriented languages. Its syntax format is as follows:

void __destruct ( void )
Example
<?php
class MyDestructableClass {
   function __construct() {
       print "构造函数\n";
       $this->name = "MyDestructableClass";
   }
   function __destruct() {
       print "销毁 " . $this->name . "\n";
   }
}
$obj = new MyDestructableClass();
?>
executes the above code, and the output result is:
构造函数
销毁 MyDestructableClass

Inheritance

PHP uses the keyword extends to inherit a class. PHP does not support multiple inheritance. The format is as follows:

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

Example

The Child_Site class in the example inherits the Site class and extends the functions:

<?php 
// 子类扩展站点类别
class Child_Site extends Site {
   var $category;
function setCate($par){
$this->category = $par;
}
  
function getCate(){
echo $this->category . PHP_EOL;
}
}

Method overriding

If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method rewriting.

The getUrl and getTitle methods are overridden in the example:

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

Access control

PHP pairs attributes or Access control of methods is achieved by adding the keywords public, protected or private in front.

  • public (public): Public class members can be accessed from anywhere.

  • protected (protected): Protected class members can be accessed by itself and its subclasses and parent classes.

  • private (private): Private class members can only be accessed by the class in which they are defined.

Access control of attributes

Class attributes must be defined as one of 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
?>

Method access control

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

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

The interface is defined through the interface keyword, just like defining a standard class, but all methods defined in it are empty.

All methods defined in the interface must be public. This is a characteristic of the interface.

To implement an interface, use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. A 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 define a value that always remains unchanged in the class as a constant. There is no need to use the $ symbol when defining and using constants.

The value of a constant must be a fixed value and cannot be a variable, class attribute, the result of a mathematical operation or a function call.

Since PHP 5.3.0, you can use a variable to dynamically call a class. But the value of this 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 at least one method in it is Declared as abstract, then the class must be declared as abstract.

Classes defined as abstract cannot be instantiated.

A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation.

When inheriting an abstract class, the subclass must define all abstract methods in the parent class; in addition, the access control of these methods must be the same (or more relaxed) as in the parent class. For example, if an abstract method is declared as protected, then the method implemented in the subclass should be declared as protected or public, and cannot be defined as private. In addition, the method calling method must match, that is, the type and number of required parameters must be consistent. For example, if a subclass defines an optional parameter that is not included in the declaration of an abstract method of the parent class, there is no conflict between the two declarations.

<?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;
?>
executes the above code, and the output result is:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Static keyword

Declaring a class attribute or method as static allows direct access without instantiating the class.

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

Since static methods do not require an object to be called, the pseudo variable $this is not available in static methods.

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

Since PHP 5.3.0, you can use a variable to dynamically call a class. But the value of this variable cannot be the keywords 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;
?>
executes the above program, and the output result is:
foo
foo

Final Keywords

PHP 5 adds a new final keyword. If 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.

An error will be reported when executing the following code:

<?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 will not The constructor of the class automatically calls the constructor of the parent class. To execute the constructor of the parent class, you need to call parent::__construct() in the constructor of the subclass.

<?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();
?>
executes the above program, and the output result is:
BaseClass 类中构造方法
BaseClass 类中构造方法
SubClass 类中构造方法
BaseClass 类中构造方法




php.cn