English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In object-oriented programming (English: Object-Oriented programming, abbreviated as OOP, in which an object is an integrated whole consisting of descriptions of information and the processing of information, and is an abstraction of the real world.
In the real world, the things we face are all objects, such as computers, televisions, bicycles, and so on.
The main three characteristics of objects:
Behavior of objects: Operations that can be performed on objects, such as turning on and off the lights, are behaviors.
Form of objects: When methods are applied, how objects respond, color, size, shape.
Representation of objects: The representation of objects is equivalent to an ID card, and the specific distinction lies in what is different in the same behaviors and states.
For example, Animal (animal) is an abstract class, and we can be specific to a dog and a sheep, while a dog and a sheep are specific objects, they have color attributes, can write, can run, and so on.
Class It defines the abstract characteristics of a thing. The definition of a class includes the form of data and the operations on the data.
Object It is an instance of a class.
Member variables It is a variable defined within the class. Its value is not visible to the outside world, but it can be accessed through member functions. After the class is instantiated into an object, this variable can be called the object's attribute.
Member function It is defined within the class and can be used to access the data of the object.
inheritance Inheritance is the mechanism by which subclasses automatically share the data structures and methods of the superclass, which is a relationship between classes. When defining and implementing a class, it can be done on the basis of an already existing class, taking the content defined by the existing class as its own content and adding some new content.
Superclass A class that is inherited by another class can be called a superclass, or base class, or superclass.
Subclass A class that inherits from another class is called a subclass, or derived class.
Polymorphism Polymorphism refers to the same function or method acting on multiple types of objects and obtaining different results. Different objects can produce different results when receiving the same message, and this phenomenon is called polymorphism.
Overloading Simply put, it is the situation where functions or methods have the same name but different parameter lists. Such functions or methods with the same name but different parameters are referred to as overloaded functions or methods.
Abstractness Abstractness refers to abstracting objects with consistent data structures (attributes) and behaviors (operations) into classes. A class is such an abstraction that reflects important properties related to the application while ignoring some irrelevant content. Any classification of classes is subjective, but it 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 It is mainly used to initialize an object when creating an object, that is, to assign initial values to the object's member variables, and is always used together with the new operator in statements creating objects.
Destructor − Destructor (destructor) is the opposite of the constructor. When the object ends its lifecycle (for example, the function in which the object is located has been called), the system automatically executes the destructor. The destructor is often used for "cleaning up" work (for example, if a memory space is allocated with new when an object is created, it should be released with delete before exiting).
In the figure below, we created three objects: Mercedes, Bmw, and Audi through the Car class.
$mercedes = new Car(); $bmw = new Car(); $audi = new Car();
The syntax format for defining PHP classes is usually as follows:
<?php class phpClass { var $var1; var $var2 ="constant string"; function myfunc ($arg1, $arg2) { [..] } [..] } ?>
The analysis is as follows:
Class usage class The keyword followed by the class name defines.
a pair of curly braces ({}) after the class name to define variables and methods.
Class variables use var to declare, variables can also be initialized with values.
Function definition is similar to PHP function definition, but the function can only be accessed through the class and its instantiated objects.
<?php class Site { /* Member variables */ var $url; var $title; /* Member function */ 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 itself.
PHP_EOL for newline characters.
After the class is created, we can use new The operator to instantiate the object of the class:
$w3codebox = new Site; $taobao = new Site; $google = new Site;
The above code creates three objects, each of which is independent. Next, let's see how to access member methods and member variables.
After creating an instance of the object, we can use the object to call member methods, and the member methods can only operate the member variables of the object:
// Invoke member function to set title and URL $w3codebox->setTitle("Basic Tutorial Website"); $taobao->setTitle("Taobao"); $google->setTitle("Google Search"); $w3codebox->setUrl('www.w');3>setUrl('codebox.com'); $taobao->setUrl('www.taobao.com'); $google->setUrl('www.google.com'); // Call member functions to get the title and URL $w3codebox->getTitle(); $taobao->getTitle(); $google->getTitle(); $w3codebox->getUrl(); $taobao->getUrl(); $google->getUrl();
The complete code is as follows:
<?php class Site { /* Member variables */ var $url; var $title; /* Member function */ 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; } } $w3codebox = new Site; $taobao = new Site; $google = new Site; // Invoke member function to set title and URL $w3codebox->setTitle("Basic Tutorial Website"); $taobao->setTitle("Tmall Mall"); $google->setTitle("Google Search"); $w3codebox->setUrl('www.w');3>setUrl('codebox.com'); $taobao->setUrl('www.tmall.com'); $google->setUrl('www.google.com'); // Call member functions to get the title and URL $w3codebox->getTitle(); $taobao->getTitle(); $google->getTitle(); $w3codebox->getUrl(); $taobao->getUrl(); $google->getUrl(); ?>
When executing the above code, the output result is:
Basic Tutorial Website Tmall Mall Google Search www.oldtoolbag.com www.tmall.com www.google.com
The constructor is a special method. It is mainly used to initialize an object when creating an object, that is, to assign initial values to the object member variables, and is used with the new operator in the statement for creating an object.
PHP 5 Allows developers to define a method as a constructor in a class, and 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 setTitle and setUrl methods:
$w3codebox = new Site('www.w',3codebox.com', 'Basic Tutorial Website'); $tmall = new Site('www.tmall.com', 'Tmall Mall'); $google = new Site('www.google.com', 'Google Search'); // Call member functions to get the title and URL $w3codebox->getTitle(); $tmall->getTitle(); $google->getTitle(); $w3codebox->getUrl(); $tmall->getUrl(); $google->getUrl();
The destructor (destructor) is the opposite of the constructor. When an object ends its lifecycle (for example, when the function containing the object has been called), the system automatically executes the destructor.
PHP 5 The concept of destructor is introduced, which is similar to other object-oriented languages, and its syntax format is as follows:
void __destruct(void)
<?php class MyDestructableClass { function __construct() { print "Constructor\n"; $this-name = "MyDestructableClass"; } function __destruct() { print "Destroy " . $this->name . "\n"; } } $obj = new MyDestructableClass(); ?>
When executing the above code, the output result is:
Constructor Destroy MyDestructableClass
PHP uses the keyword extends To inherit a class, PHP does not support multiple inheritance, and the format is as follows:
class Child extends Parent { // Code section }
In the example, the Child_Site class inherits from the Site class and extends the functionality:
<?php // Subclass 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 does not meet the needs of the subclass, it can be rewritten, which is called method overriding (override) or method rewriting.
In the example, the getUrl and getTitle methods are overridden:
function getUrl() { echo $this->url . PHP_EOL; return $this->url; } function getTitle() { echo $this->title . PHP_EOL; return $this->title; }
PHP implements access control for attributes or methods by adding the keywords public (public), protected (protected), or private (private) in front of them.
public (public):Public class members can be accessed anywhere.
protected (protected):Protected class members can be accessed by their own class, subclasses, and parent classes.
private (private):Private class members can only be accessed by the class they are defined in.
Class properties must be defined as 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 cause a fatal error echo $obj->private; // This line will also produce a fatal error $obj->printHello(); // Output Public, Protected, and Private /** *Define MyClass2 */ class MyClass2 extends MyClass { // Public and protected can be redefined, but not private protected $protected = 'Protected'2'; 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; // Undefined private echo $obj2->protected; // This line will cause a fatal error $obj2->printHello(); // Output Public, Protected2 and Undefined ?>
Methods in the class can be defined as public, private, or protected. If these keywords are not set, the method is default 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 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 cause a fatal error $myclass->MyPrivate(); // This line will cause a fatal error $myclass->Foo(); // Public, protected, and private methods can all be executed /** * Define MyClass2 */ class MyClass2 extends MyClass { // This method is public function Foo2(); { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // This line will cause a fatal error } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // This line can be executed normally $myclass2->Foo2(); // Both public and protected methods can be executed, but not private ones 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 ?>
Using interfaces (interface), you can specify which methods a class must implement, but you do not need to define the specific content of these methods.
Interfaces are defined by keyword, just like defining a standard class, but all the methods defined in it are empty. Interfaces are defined using the
All methods defined in the interface must be public, which is a feature of interfaces.
To implement an interface, use implements The class must implement all the methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces, and multiple interface names are separated by commas.
<?php // Declare an 'iTemplate' interface interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // Implement interface class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this-vars[$name] = $var; } public function getHtml($template) { foreach($this-foreach($vars as $name => $value) { $template = str_replace('{'. $name .'}', $value, $template); } return $template; } }
Values that remain unchanged in a class can be defined as constants. No $ symbol is needed when defining and using constants.
The value of a constant must be a fixed value and cannot be a variable, class property, result of a mathematical operation, or function call.
Since PHP 5.3. Starting from version 0, a variable can be used to dynamically call the class. However, the value of the variable cannot be a keyword (such as self, parent, or static).
<?php class MyClass { const constant = '常量值'; function showConstant() { echo self::constant . PHP_EOL; } } echo MyClass::constant . PHP_EOL; $classname = "MyClass"; echo $classname::constant . PHP_EOL; // from 5.3.0 starts $class = new MyClass(); $class->showConstant(); echo $class::constant . PHP_EOL; // from PHP 5.3.0 starts ?>
Any class that has at least one method declared as abstract must be declared as abstract.
Classes defined as abstract cannot be instantiated.
Abstract methods only declare the calling method (parameters) and cannot define the specific functional implementation.
When inheriting an abstract class, the subclass must define all the abstract methods in the superclass; in addition, the access control of these methods must be the same as, or more lenient than, those in the superclass. For example, if an abstract method is declared as protected, then the method implemented in the subclass should also be declared as protected or public, and cannot be defined as private.
<?php abstract class AbstractClass { // These methods must be defined by the subclass abstract protected function getValue(); abstract protected function prefixValue($prefix); // Normal 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; ?>
When executing the above code, the output result is:
ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
In addition, the subclass method can include optional parameters that do not exist in the superclass abstract method.
For example, if a subclass defines an optional parameter while the declaration of the abstract method in the superclass does not, it can still run normally.
<?php abstract 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 parameters that do not exist in the superclass signature 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 as follows:
Mr. Pacman Mrs. Pacwoman
By declaring class properties or methods as static (static), you can access them without instantiating the class.
Static properties cannot be accessed through an object that has already instantiated 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 through -> operator to access.
Since PHP 5.3Starting from version .0, you can dynamically call a class using a variable. However, the value of the 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; ?>
After executing the above program, the output is:
foo foo
PHP 5 A final keyword has been added. If a method in the superclass is declared as final, the subclass cannot override this method. If a class is declared as final, it cannot be inherited.
The following code execution will result in 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; } } // Error message: Fatal error: Cannot override final method BaseClass::moreTesting() ?>
PHP does not automatically call the constructor of the superclass in the constructor of the subclass. To call the constructor of the superclass, you need to call it in the constructor of the subclass. parent::__construct() .
<?php class BaseClass { function __construct() { print "BaseClass class constructor" . PHP_EOL; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); // The constructor of the subclass cannot automatically call the constructor of the superclass print "SubClass class constructor" . PHP_EOL; } } class OtherSubClass extends BaseClass { // Inheriting the constructor of BaseClass } // Calling BaseClass constructor $obj = new BaseClass(); // Calling constructors of BaseClass and SubClass $obj = new SubClass(); // Calling BaseClass constructor $obj = new OtherSubClass(); ?>
After executing the above program, the output is:
BaseClass class constructor BaseClass class constructor SubClass class constructor BaseClass class constructor