PHP object-oriented

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. An abstraction of the real world.

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

The main three characteristics of objects:

· Object behavior: What operations can be applied to the object, turning on the light and turning off the light are behaviors.

· Object Form: When those methods are applied to how the object responds, color, size, appearance.

· Representation of objects: The representation of objects is equivalent to an ID card. It specifically distinguishes the differences between the same behaviors and states.

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

QQ图片20161009105306.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 − define variables 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 − Definition inside the class, which can be used to access the data of the object.

· Inheritance − Inheritance is a mechanism for subclasses to automatically share the 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.

· The parent class − A class is inherited by other classes, which can be called the parent class, or the base class, or the 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 and different parameters are called overloaded functions or methods.

·                                                                                                                                                                                                             . 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 together the properties and behavior of an object that exists in the real world and placing it within a logical unit.

·    Constructor − It is 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 in the statement to create the object.

·                                                                               − 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. 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 ();

QQ图片20161009105253.png


##PHP Class Definition

PHP The usual syntax format for defining a class is as follows:

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

The analysis is as follows:

·       Classes are defined using the class keyword followed by the class name.

·    Variables and methods can be defined within a pair of curly brackets ({}) after the class name.

· Class variables are declared using var, and variables can also be initialized.

·           Function definition is similar to the definition of PHP function, but the function 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;
  }
}
?>

Variable $this represents its own object.

PHP_EOL is the newline character.


Create objects in PHP

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

$runoob = new Site;

$taobao = new Site;

$google = new Site;

We created three objects in the above code. 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 on the object. Member variables:

// Call the member function and set the title and URL

$runoob->setTitle( "PHP Chinese Network" );

$taobao-> setTitle( "Taobao" );

$google->setTitle( "Google Search" );

$runoob->setUrl( 'www.ask. php.cn' );

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

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

// Call the member function to get the title and URL

$runoob->getTitle();

$taobao->getTitle( );

$google->getTitle();

$runoob->getUrl();

$taobao->getUrl ();

$google->getUrl();

The complete code is as follows:

Example

<?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; 
   } 
 } 
 
 $runoob = new Site; 
 $taobao = new Site; 
 $google = new Site; 
 
 // 调用成员函数,设置标题和URL 
 $runoob->setTitle( " PHP中文网" ); 
 $taobao->setTitle( "淘宝" ); 
 $google->setTitle( "Google 搜索" ); 
 
 $runoob->setUrl( 'www. ask.php.cn ' ); 
 $taobao->setUrl( 'www.taobao.com' ); 
 $google->setUrl( 'www.google.com' ); 
 
 // 调用成员函数,获取标题和URL 
 $runoob->getTitle(); 
 $taobao->getTitle(); 
 $google->getTitle(); 
 
 $runoob->getUrl(); 
 $taobao->getUrl(); 
 $google->getUrl(); 
 ?>


Execute the above code, the output result is:

PHP Chinese website

Taobao

Google search

www.ask.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 the $url and $title variables through the constructor method:

function __construct( $par1, $par2 ) {

$this- >url = $par1;

$this->title = $par2;

}

Now we no longer need to call the setTitle and setUrl methods:

Example

$runoob = new Site('www.runoob.com', 'PHP中文网'); 
 $taobao = new Site('www.taobao.com', '淘宝'); 
 $google = new Site('www.google.com', 'Google 搜索'); 
 
 // 调用成员函数,获取标题和URL 
 $runoob->getTitle(); 
 $taobao->getTitle(); 
 $google->getTitle(); 
 
 $runoob->getUrl(); 
 $taobao->getUrl(); 
 $google->getUrl();



#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();
?>

Execute the above code, the output result is:

Constructor

Destroy 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 {

// Code part

}

Instance

The Child_Site class in the instance inherits the Site class and extends the functionality:

<?php

// Child class extends site category

class Child_Site extends Site {

var $category;

Function Setcate ($ Par) {

$ This-& GT; Category = $ Par;

##}

# Echo $ This- & GT; Category. PHP_EOL;

##}

##}

## This

#Method rewriting


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 called method rewriting. The getUrl and getTitle methods are rewritten 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 access control to properties or methods is achieved by adding the keywords public (public), protected (protected) or private (private) in front. · PUBLIC (Public): Public members can be accessed anywhere.
# · Protected: The protected members can be accessed by them and their subclasses and parent class.

· Prive (private): Private class members can only be accessed by their class.

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 not The specifics of these methods need to be defined. 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 there is at least one in it If the method is declared abstract, then the class must be declared 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 methods 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;
?>

Execute the above code, 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;
?>

        

Execute the above program, the output result is:

foo

foo

Final keyword

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 No The constructor of the parent class will be automatically called in the constructor of the subclass. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.

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

Execute the above program, the output result is:

Construction method in BaseClass class

Construction method in BaseClass class

Construction method in SubClass class

Construction method in BaseClass class


Continuing Learning
||
<?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(); ?>
submitReset Code