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, and is an abstraction of the real world. OOP achieves three goals of software engineering: reusability, flexibility, and extensibility.
PHP has improved its support for OOP after version 4.0. For small applications, it may be simpler and more efficient to use traditional procedural programming. However, for large and complex applications, OOP is a choice that must be considered.
Class
A class is a collection of objects with the same properties and services. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: properties and services. In object-oriented programming languages, a class is an independent program unit. It should have a class name and include two main parts: attribute description and service description.
Object
An object is an entity used to describe objective things in the system. It is a basic unit that constitutes the system. An object consists of a set of properties and a set of services that operate on the set of properties.
In the real world, the things we face are objects, such as computers, televisions, bicycles, etc.
The main three characteristics of the object:
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, 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.
The relationship between classes and objects
The relationship between classes and objects is like the relationship between molds and castings. The instantiation result of a class is an object, and the abstraction of a type of object is a class.
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. .
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 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.
Parent class − A class is inherited by other classes. This class can be called a parent class, a base class, or a 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. .
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 the properties and behavior of an object that exists in the real world together and placing it 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 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 ();
PHP class definition
Use the keyword class to declare a class, followed by the name of the class, and the body is enclosed in {} symbols stand up.
Syntax:
class class_name{
...
}
The class contains attributes and methods.
By using the keyword var in the class definition to declare variables, the attributes of the class are created, also called member attributes of the class.
Syntax:
class class_name{
var $var_name;
}
By declaring the function in the class definition , that is, the method of the class is created.
grammar:
class class_name{
function function_name(arg1,arg2,......)
{
Function code
}
}
A class with defined attributes and methods is a complete class, and a complete processing logic can be included in a class. Use the new keyword to instantiate an object in order to apply logic within the class. Multiple objects can be instantiated simultaneously.
Syntax:
object = new class_name();
After instantiating an object, use the -> operator to access the members of the object Properties and methods.
Syntax:
object->var_name;
object->function_name;
If you want to access members in the defined class For attributes or methods, you can use the pseudo variable $this. $this is used to represent the current object or the object itself.
<?php class Person { //人的成员属性 var $name; //人的名字 var $age; //人的年龄 //人的成员 say() 方法 function say() { echo "我的名字叫:".$this->name." <br >"; echo "我的年龄是:".$this->age; } } //类定义结束 //实例化一个对象 $p1 = new Person(); //给 $p1 对象属性赋值 $p1->name = "张三"; $p1->age = 20; //调用对象中的 say()方法 $p1->say(); ?>
Run this example, output:
My name is: Zhang San
My age is: 20
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; } } $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(); ?>
Running example»
Execute the above code, the output result is:
php Chinese website
Taobao
Google Search
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. When using the new operator to create an instance of a class, the constructor will be called automatically, and its name must be __construct()
Only one constructor can be declared in a class, and only when an object is created each time The constructor method will be called once every time. This method cannot be called actively, so it is usually used to perform some useful initialization tasks. This method has no return value.
Syntax:
function __construct(arg1,arg2,...)
{
......
}
In the above example, we can initialize the $url and $title variables through the constructor method:
<?php
function __construct( $ par1, $par2 ) {
$this->url = $par1;
$this->title = $par2;
}
?>
Now we no longer need to call the setTitle and setUrl methods:
Instance
<?php $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»
Destructor
Corresponding to the constructor method is the destructor method. The destructor method allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc. The destructor cannot take any parameters and its name must be __destruct() .
PHP 5 introduced the concept of destructor, which is similar to other object-oriented languages. Its syntax format is as follows:
function __destruct()
{
......
}
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
The constructor and destructor are used simultaneously
<?php class Person { var $name; var $age; //定义一个构造方法初始化赋值 function __construct($name,$age) { $this->name=$name; $this->age=$age; } function say() { echo "我的名字叫:".$this->name." <br >"; echo "我的年龄是:".$this->age." <br >";; } function __destruct() { echo "再见".$this->name; } } $p1=new Person("张三", 20); $p1->say(); ?>
to execute the above code, the output result is:
My name is: Zhang San
’s age is: 20
Goodbye Zhang San
Inheritance
PHP class Inheritance refers to creating a new derived class that inherits data and methods from one or more previously defined classes, and can redefine or add new data and methods, thus establishing a class hierarchy or hierarchy.
We call the existing class used to derive the new class as the parent class, and the new class derived from the existing class is the subclass. Inheritance is one of the three major characteristics of object-oriented.
Through the inheritance mechanism, existing data types can be used to define new data types. The new data type defined not only has the newly defined members, but also has the old members.
Note: Unlike languages such as Java, in PHP, a class can only directly inherit data from one class, that is, single inheritance.
Use the extends keyword to define class inheritance:
class subclass extends parent class{
}
Instance
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 override
If the method inherited from the parent class cannot satisfy the requirements of the subclass Requirements can be rewritten. This process is called method override, also known as 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 and encapsulation
This is achieved in PHP by adding the access modifier public, protected or private in front Access control for properties or methods. Access modifiers of type
allow developers to control access to class members, which is a feature of OOP languages.
PHP supports the following three access modifiers:
public (public): members in the class will have no access restrictions, and all external members can access (read and write) this class Members (including member properties and member methods). If a member of a class does not specify a member access modifier, it will be treated as public.
protected (protected): Members defined as protected cannot be accessed by external code of the class, but subclasses of the class have access rights.
private (private): A member defined as private allows access to all members in the same class, but access to external code and subclasses of the class is not allowed.
Modifier access permission comparison table:
Public Protected Private
# √ All external members √ √
<?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 controlMethods 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 ?>EncapsulationEncapsulation is to combine the attributes and services of a class (object) into an independent unit, hide the internal details as much as possible, and only retain the necessary interfaces to communicate with the outside. . This encapsulation feature effectively ensures the independence of objects, enables localization of software errors, and greatly reduces the difficulty of error checking and troubleshooting. Use the private keyword to encapsulate properties and methods:
<?php class Person { //将成员属性定义为 private private $name; private $age; //定义一个构造方法初始化赋值 function __construct($name, $age) { $this->name=$name; $this->age=$age; } function say() { echo "我的名字叫:".$this->name." <br >"; echo "我的年龄是:".$this->age; } } $p1=new Person("张三", 20); $p1->say(); ?>
Interface
PHP classes are single inheritance, that is, they are not Supports multiple inheritance. When a class requires the functions of multiple classes, inheritance is powerless. For this reason, PHP introduces class interface technology. If all the methods in an abstract class are abstract methods and no variables are declared, and all members in the interface have public permissions, then this special abstract class is called an interface.
<?php //定义接口 interface User{ function getDiscount(); function getUserType(); } //VIP用户 接口实现 class VipUser implements User{ // VIP 用户折扣系数 private $discount = 0.8; function getDiscount() { return $this->discount; } function getUserType() { return "VIP用户"; } } class Goods{ var $price = 100; var $vc; //定义 User 接口类型参数,这时并不知道是什么用户 function run(User $vc){ $this->vc = $vc; $discount = $this->vc->getDiscount(); $usertype = $this->vc->getUserType(); echo $usertype."商品价格:".$this->price*$discount; } } $display = new Goods(); $display ->run(new VipUser);//可以是更多其他用户类型 ?>Result:VIP user product price: 80 yuan
PHP can also implement multiple interfaces at the same time when inheriting a class:
class subclass extends parent class implementtns interface 1, interface 2, ...
{
......
}
The difference between abstract classes and interfaces
Interfaces are special abstract classes and can also be regarded as the specification of a model. The general difference between an interface and an abstract class is as follows:
If a subclass implements an interface, it must implement all methods in the interface (whether needed or not); if it inherits an abstract class, it only needs to implement the required methods. Can.
If the method name defined in an interface changes, then all subclasses that implement this interface need to update the method name synchronously; and if the method name changes in an abstract class, the method name corresponding to its subclass will not be affected. The impact is just that it becomes a new method (implemented relative to the old method).
Abstract classes can only be inherited singly. When a subclass needs to implement functions that need to be inherited from multiple parent classes, interfaces must be used.
Constant
Use the const keyword to define constants in a class instead of the usual define() function.
You can define values that remain unchanged in the class 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, 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).
Syntax
const constant = "value";
Example:
<?php Class Person{ // 定义常量 const country = "中国"; public function myCountry() { //内部访问常量 echo "我是".self::country."人 <br >"; } } // 输出常量 echo Person::country." <br >"; // 访问方法 $p1 = new Person(); $p1 -> myCountry(); ?>
Run output:
China
I am Chinese
Abstract class
Any class, if at least one method in it is declared as abstract, then this 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 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
Statement If a class attribute or method is static, it can be accessed 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, 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 Person{ // 定义静态成员属性 public static $country = "中国"; // 定义静态成员方法 public static function myCountry() { // 内部访问静态成员属性 echo "我是".self::$country."人<br >"; } } class Student extends Person { function study() { echo "我是". parent::$country."人<br >"; } } // 输出成员属性值 echo Person::$country."<br >";// 输出:中国 $p1 = new Person(); //echo $p1->country;// 错误写法 // 访问静态成员方法 Person::myCountry();// 输出:我是中国人 // 静态方法也可通过对象访问: $p1->myCountry(); // 子类中输出成员属性值 echo Student::$country."<br >";// 输出:中国 $t1 = new Student(); $t1->study();// 输出:我是中国人 ?>
Run output:
中国
我是中国人
我是中国人
中国
我是中国人
Final Key Word
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.
final class Person
{
......
}
The following code will report an error when executed:
<?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 automatically call the parent class constructor in the subclass constructor. 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 the BaseClass class
Construction method in the BaseClass class
Construction method in the SubClass class
Construction method in the BaseClass class