Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Object-Oriented

PHP Object-Oriented

Object-Oriented (OO) is a programming paradigm and method that encapsulates the data in a program and the methods that operate on that data together into "objects", and accomplishes program functions through interaction and message passing between objects. Object-oriented programming emphasizes encapsulation, inheritance, polymorphism, and dynamic binding of data, giving programs better extensibility, maintainability, and reusability.

In object-oriented programming (OOP), an object is a whole composed of information and descriptions of how to process that information; it is an abstraction of the real world.

Everything we face in the real world is an object, such as computers, televisions, bicycles, etc.

The three main characteristics of an object:

For example, Animal is an abstract class; we can be specific to a dog and a sheep, and the dog and sheep are concrete objects. They have color attributes, and can write, run, and other behaviors/states.

The three main characteristics of object-oriented programming:


Object-Oriented Content

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


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


PHP Class Definition

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



The analysis is as follows:

Example


url = $par;
  }
  
  function getUrl(){
     echo $this->url . PHP_EOL;
  }
  
  function setTitle($par){
     $this->title = $par;
  }
  
  function getTitle(){
     echo $this->title . PHP_EOL;
  }
}
?>

Variables $this Represents the object itself.

PHP_EOL is a newline character.


Creating Objects in PHP

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


$runoob = new Site;
$taobao = new Site;
$google = new Site;

In the code above, we created three objects, each independent of the others. Next, let's see how to access member methods and member variables.

Calling Member Methods

After instantiating an object, we can use that object to call member methods; the object's member methods can only operate on that object's member variables:


// Call member function to set title and URL
$runoob->setTitle( "Runoob Tutorial" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );

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

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

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

The complete code is as follows:

Example

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 ; // call member functions, set title and URL $runoob -> setTitle ( "Runoob Tutorial" ); $taobao -> setTitle ( "Taobao" ); $google -> setTitle ( "Google Search" ); $runoob -> setUrl ( 'www.runoob.com' ); $taobao -> setUrl ( 'www.taobao.com' ); $google -> setUrl ( 'www.google.com' ); // call member functions, get title and URL $runoob -> getTitle (); $taobao -> getTitle (); $google -> getTitle (); $runoob -> getUrl (); $taobao -> getUrl (); $google -> getUrl (); ?>

Run Example »

The output of the code above is:


Runoob Tutorial
淘宝
Google 搜索
www.runoob.com
www.taobao.com
www.google.com

PHP Constructor

A constructor is a special method. It is mainly used to initialize an object when it is created, that is, to assign initial values to the object's member variables, used together with the new operator in the object creation statement.

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


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

In the example above, we can use the constructor method to initialize the $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

$runoob = new Site('www.runoob.com', 'Runoob Tutorial');

$taobao = new Site('www.taobao.com', 'Taobao');

$google = new Site('www.google.com', 'Google Search');

// call member functions, get title and URL

$runoob->getTitle();

$taobao->getTitle();

$google->getTitle();

$runoob->getUrl();

$taobao->getUrl();

$google->getUrl();

Run Example »


The destructor

The destructor (destructor) is the opposite of the constructor. When an object ends its life cycle (for example, when the function containing the object has finished executing), the system automatically executes the destructor.

PHP 5 introduced the concept of destructors, similar to other object-oriented languages; its syntax is as follows:


void __destruct ( void )

Example


name = "MyDestructableClass";
   }

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

$obj = new MyDestructableClass();
?>

The output of the code above 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 {
   // Code section
}

Example

In the example, the Child_Site class inherits from the Site class and extends its functionality:


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

Method Overriding

If a method inherited from the parent class cannot meet the needs of the subclass, it can be modified. This process is called method overriding (also known as method redefinition).

The example overrides the 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 implements access control for properties or methods by prefixing them with the keywords public, protected, or private.

Access Control for Properties

Class properties must be defined as public, protected, or private. If defined with var, they are treated as public.


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 and protected can be redefined, but private cannot
    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 for Methods

Methods in a class can be defined as public, private, or protected. If these keywords are not set, the method defaults to public.


MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

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


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This method is public
    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
?>

an interface

Using an interface, you can specify which methods a class must implement, without needing to define the specific content of those methods.

Interfaces are defined via interface the keyword, just like defining a standard class, but all methods defined in it are empty.

All methods defined in an interface must be public; this is a characteristic of interfaces.

To implement an interface, use implements the operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces, separated by commas.


vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

Constant

A value that always remains constant in a class can be defined as a constant. The $ symbol is not needed when defining and using constants.

The value of a constant must be a fixed value; it cannot be a variable, class property, result of a mathematical operation, or function call.

Since PHP 5.3.0, a class can be dynamically called using a variable. However, the value of that variable cannot be a keyword (such as self, parent, or static).

Example


showConstant();

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

abstract classes

Any class that has at least one method declared as abstract must itself be declared as abstract.

A class defined as abstract cannot be instantiated.

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

When inheriting an abstract class, the subclass must define all abstract methods in the parent class; additionally, the access control of these methods must be the same as (or more permissive than) in the parent class. For example, if an abstract method is declared protected, the method implemented in the subclass should be declared protected or public, not private.


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 output of the code above is:


ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

In addition, subclass methods may include optional parameters not present in the parent class's abstract method.

For example, if a subclass defines an optional parameter that is not in the parent class's abstract method declaration, it will still run normally.

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

The output is:


Mr. Pacman
Mrs. Pacwoman

Static Keyword

Declaring a class property or method as static allows it to be accessed directly without instantiating the class.

Static properties cannot be accessed through an instantiated object of the class (but static methods can).

Since static methods can be called without an object, the pseudo-variable $this is not available in static methods.

Static properties cannot be accessed by an object via the -> operator.

Since PHP 5.3.0, a class can be dynamically called using a variable. However, the value of that variable cannot be the keywords self, parent, or static.


staticValue() . PHP_EOL;
?>    

Running the above program, the output is:

foo
foo

Final Keyword

PHP 5 added a new final keyword. If a method in the parent class is declared final, the subclass cannot override it. If a class is declared final, it cannot be inherited.

The following code will cause an error:




Calling the Parent Class Constructor

PHP does not automatically call the parent class's constructor in the subclass's constructor. To execute the parent class's constructor, you need to call parent::__construct() .



Running the above program, the output is:


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