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, and is an abstraction of the real world.
In the real world, the things we face are objects, such as computers, televisions, bicycles, etc.
There are three main characteristics of objects:
The behavior of the object: What operations can be applied to the object, turning on the light and turning off the light are behaviors.
The shape of the object: how the object responds when those methods are applied, color, size, appearance.
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, can be written, can run and other behavioral states.
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 a 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 functions − are defined inside the class and can be used to access the data of the object.
Inheritance − Inheritance is a mechanism by which subclasses automatically share the data structures and methods of their parent class. 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 that is inherited by other classes can be called a parent class, a base class, or a super class.
Subclass − A class that inherits from other classes is called a subclass, or it can also be called a derived class.
Polymorphism − Polymorphism means that the same function or method 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.
Abstraction − 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 together the properties and behavior of an object that exists in the real world and placing it within a logical unit.
Constructor − 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 (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 ();
The usual syntax format for PHP definition classes is as follows:
<?phpclass 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 definitions are similar to PHP function definitions, but functions can only be accessed through the class and the objects it instantiates.
<?phpclass 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; }}?>
The variable $this represents its own object.
PHP_EOL is the newline character.
After a class is created, we can use the new operator to instantiate objects of that class:
$codercto = 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.
After instantiating an object, we can use the object to call member methods. The member methods of the object can only operate on the member variables of the object:
// Call the member function to set the title and URL $codercto->setTitle( "Coder Tutorial" );$taobao->setTitle( "Taobao" );$google->setTitle( "Google Search" );$codercto-> setUrl( 'www.codercto.com' );$taobao->setUrl( 'www.taobao.com' );$google->setUrl( 'www.google.com' );// Call the member function to get the title and URL $codercto->getTitle();$taobao->getTitle();$google->getTitle();$codercto->getUrl();$taobao->getUrl( );$google->getUrl();
The complete 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 ; }} $codercto = new Site ; $taobao = new Site ; $google = new Site ; // Call member function, set title and URL $codercto -> setTitle ( "Coder Tutorial" ); $taobao -> setTitle ( " Taobao" ); $google -> setTitle ( "Google Search" ); $codercto -> setUrl ( 'www.codercto.com' ); $taobao -> setUrl ( 'www.taobao.com' ); $google -> setUrl ( 'www.google.com' ); // Call the member function to get the title and URL $codercto -> getTitle (); $taobao -> getTitle (); $google -> getTitle (); $codercto -> getUrl (); $taobao -> getUrl (); $google -> getUrl (); ?>
Executing the above code, the output result is:
Code farmer tutorial Taobao Google search www.codercto.comwww.taobao.comwww.google.com
Constructor is a special kind of method. It is mainly used to initialize the object when creating the object, that is, assign initial values to the object member variables, and use it with new
operator in the statement to create the object.
PHP 5 allows developers to define a method as a constructor in a class, with the following syntax:
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:
$codercto = new Site('www.codercto.com', 'Coder Tutorial');$taobao = new Site('www.taobao.com', 'Taobao');$google = new Site('www.google .com', 'Google Search');// Call the member function to get the title and URL $codercto->getTitle();$taobao->getTitle();$google->getTitle();$codercto->getUrl();$taobao->getUrl();$google ->getUrl();
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 destructors, which is similar to other object-oriented languages. Its syntax is as follows:
void __destruct ( void )
<?phpclass MyDestructableClass { function __construct() { print "constructorn"; $this->name = "MyDestructableClass"; } function __destruct() { print "destroy" . $this->name . "n"; }}$obj = new MyDestructableClass();?>
Executing the above code, the output result is:
Constructor destroys MyDestructableClass
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}
In the example, the Child_Site class inherits the Site class and extends its functions:
<?php // Child class extends site category class Child_Site extends Site { var $category; function setCate($par){ $this->category = $par; } function getCate(){ echo $this->category . PHP_EOL; }}
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;}
PHP's access control to properties or methods is achieved by adding the keywords public (public), protected (protected) or private (private) in front.
public: Public class members can be accessed from anywhere.
protected: Protected class members can be accessed by itself and its subclasses and parent classes.
Private: Private class members can only be accessed by the class in which they are defined.
Class attributes must be defined as one of public, protected, or 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; // This line can be executed normally echo $obj->protected; // This line will generate a fatal error echo $obj->private; // This line will also generate a fatal error $obj->printHello(); // Output Public, Protected and Private/** * Define MyClass2 */ class MyClass2 extends MyClass{ // Public and protected can be redefined, but private but not protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; }}$obj2 = new MyClass2();echo $obj2->public; // This line can be executed normally echo $obj2->private; // privateecho is not defined $obj2->protected; // This line will generate a fatal error $obj2->printHello(); // Output Public, Protected2 and Undefined?>
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{ // Declare a public constructor public function __construct() { } // Declare a public method public function MyPublic() { } // Declare a protected Method protected function MyProtected() { } // Declare a private method private function MyPrivate() { } // This method is a public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); }}$myclass = new MyClass;$myclass->MyPublic(); // This line can be executed normally $myclass->MyProtected(); // This line will generate a fatal error $myclass->MyPrivate(); // This line will generate a fatal error $myclass->Foo(); // Public, protected, and private can all be executed/** * Define MyClass2 */class MyClass2 extends MyClass{ // This method is a public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // This line will generate A fatal error}}$myclass2 = new MyClass2;$myclass2->MyPublic(); // This line can be executed normally $myclass2->Foo2(); // Both public and protected ones can be executed, but private ones cannot. class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar: :testPublicn"; } private function testPrivate() { echo "Bar::testPrivaten"; }}class Foo extends Bar { public function testPublic() { echo "Foo::testPublicn"; } private function testPrivate() { echo "Foo::testPrivaten"; }}$myFoo = new foo();$myFoo->test(); // Bar::testPrivate // Foo::testPublic?>
Using an interface, you can specify which methods a class must implement, but you do not need to define the specific content of these methods.
An 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 an interface must be public. This is a characteristic of interfaces.
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// Declare an 'iTemplate' interface interface iTemplate{ public function setVariable($name, $var); public function getHtml($template);}// Implement the interface 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; }}
Values that remain unchanged throughout a class can be defined as constants. 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, classes can be called dynamically using a variable. But the value of this variable cannot be a keyword (such as self, parent or static).
<?phpclass MyClass{ const constant = 'constant value'; function showConstant() { echo self::constant . PHP_EOL; }}echo MyClass::constant . PHP_EOL;$classname = "MyClass";echo $classname::constant . PHP_EOL; // Since 5.3.0 $class = new MyClass();$class->showConstant();echo $class::constant . PHP_EOL; // Since PHP 5.3.0?>
Any class must be declared abstract if at least one method in it is 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.
<?phpabstract class AbstractClass{ // Mandatory for subclasses to define these methods abstract protected function getValue(); abstract protected function prefixValue($prefix); // Ordinary method (non-abstract method) 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;?>
Executing the above code, the output result is:
ConcreteClass1FOO_ConcreteClass1ConcreteClass2FOO_ConcreteClass2
Additionally, child class methods can contain optional parameters that are not present in the parent class abstract method.
For example, if a subclass defines an optional parameter that is not included in the declaration of the abstract method of the parent class, it can still run normally.
<?phpabstract class AbstractClass{ // Our abstract method only needs to define the required parameters abstract protected function prefixName($name);}class ConcreteClass extends AbstractClass{ // Our subclass can define optional options that do not exist in the parent class signature Parameters 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. PacmanMrs. Pacwoman
By declaring a class attribute or method as static, you can access it directly 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, classes can be called dynamically using a variable. But the value of this variable cannot be the keywords self, parent or static.
<?phpclass 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;?>
Executing the above program, the output result is:
foofoo
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:
<?phpclass 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; }}// Error message Fatal error: Cannot override final method BaseClass::moreTesting()?>
PHP will not automatically call the parent class's constructor in the child class's constructor. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.
<?phpclass BaseClass { function __construct() { print "Constructor method in BaseClass class" . PHP_EOL; }}class SubClass extends BaseClass { function __construct() { parent::__construct(); // The subclass constructor cannot automatically call the parent The constructor method of the class print "Constructor method in SubClass class" . PHP_EOL; }}class OtherSubClass extends BaseClass { // Inherit the constructor method of BaseClass}// Call the BaseClass constructor $obj = new BaseClass(); // Call the BaseClass and SubClass constructors $obj = new SubClass(); // Call the BaseClass constructor $obj = new OtherSubClass();?>
Executing the above program, the output result is:
Constructor method in BaseClass class Constructor method in Class SubClass Constructor method in BaseClass class