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. It is 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 the object:
· The behavior of the object: what operations can be applied to the object, turn on the light, turn off the light The light is the action.
· 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. It specifically distinguishes the differences between the same behaviors and states.
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. .
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. method.
· 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 attributes and behaviors of an object existing in the real world and placing them 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
##PHP The usual syntax format for defining a class is as follows:
is parsed as follows:
· Class usage Add the class name definition after the class keyword. · Variables and methods can be defined within a pair of braces ({}) after the class name. · Class variables are declared using var, and variables can also be initialized. · Function definition is similar to PHP function definition, but functions can only be accessed through the class and its instantiated objects.Instance
url = $par; } function getUrl(){ echo $this->url ."
"; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title . "
"; } }?>
##Variable $this represents its own object.
Creating objects in PHPAfter a class is created, we can use the new operator to instantiate objects of this class:
$php = new Site;
$taobao = new Site;
$google = new Site;
In the above code, we created three objects, each of which is independent. Next, let’s take a look at how to access member methods and member variables.
// Call the member function and set the title and URL
$php->setTitle( "php中文网" );
$taobao-> setTitle( "Taobao" );
$google->setTitle( "Google Search" );
$php->setUrl( 'm.sbmmt.com' );
$taobao ->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );
// Call the member function to get the title and URL
$php->getTitle();
$taobao->getTitle();
$google->getTitle();
$php->getUrl();
$taobao->getUrl();
$google->getUrl();
We combine the codes we learned above:
##The complete code is as follows:
url = $par; } function getUrl(){ echo $this->url ."
"; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title . "
"; } } $php = new Site; $taobao = new Site; $google = new Site; // 调用成员函数,设置标题和URL $php->setTitle( "php中文网" ); $taobao->setTitle( "淘宝" ); $google->setTitle( "Google 搜索" ); $php->setUrl( 'm.sbmmt.com' ); $taobao->setUrl( 'www.taobao.com' ); $google->setUrl( 'www.google.com' ); // 调用成员函数,获取标题和URL $php->getTitle(); $taobao->getTitle(); $google->getTitle(); $php->getUrl(); $taobao->getUrl(); $google->getUrl(); ?>
Program running result:
php中文网Taobao
Google search
m.sbmmt.com
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 $url and $title through the construction method Variable:
function __construct( $par1, $par2 ) {
$this->url = $par1;
$ this->title = $par2; }Now we no longer need to call the setTitle and setUrl methods:
Example
Use the constructor to simplify the above code:
url = $par; } function getUrl(){ echo $this->url ."
"; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title . "
"; } function __construct( $par1, $par2 ) { $this->url = $par1; $this->title = $par2; } } // 调用成员函数,设置标题和URL $php = new Site('m.sbmmt.com', '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(); ?>
Program running results:
php中文网
Taobao
Google Search
m.sbmmt.com
www.taobao.com
www.google.com
## Analysis Constructor
Destructor (destructor) Contrary to the constructor, when the object ends its life cycle (such as 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
name = "MyDestructableClass"; } function __destruct() { print "销毁 " . $this->name . "\n"; } } $obj = new MyDestructableClass(); ?>
Program running result:
Constructor Destroy MyDestructableClass
##InheritancePHP uses the keyword extends to inherit a class. PHP does not support multiple inheritance. Format As follows:
class Child extends Parent {// Code part
}above This means that the Child class inherits the Parent class
InstanceIn the following example, the Child_Site class inherits the Site class and extends the functionality:
category = $par; } function getCate(){ echo $this->category . "
"; } } ?>
Method rewritingIf 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 following example rewrites 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 access control to properties or methods is achieved by adding the keywords public (public), protected (protected) or private (private) in front. ·public (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.
Access control of attributes Class attributes must be defined as one of public, protected, and private. If defined with var, it is considered public.Example
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 ?>Look carefully at the above code
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.
Instance
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
Use interface (interface), you can specify which methods a certain class must implement, but you do not need to define the specific content of these methods. 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.Instance
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 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).
Instance
"; } } echo MyClass::constant . "
"; $classname = "MyClass"; echo $classname::constant . "
"; // 自 5.3.0 起 $class = new MyClass(); $class->showConstant(); echo $class::constant . "
"; // 自 PHP 5.3.0 起 ?>
Abstract class
Any A 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. In addition, the method calling method must match, that is, the type and number of required parameters must be consistent. For example, if the subclass defines an optional parameter
, but it is not included in the declaration of the abstract method of the parent class, there is no conflict between the two declarations.
Example
printOut(); echo $class1->prefixValue('FOO_') . "
"; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue('FOO_') . "
"; ?>
Program running result:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
Static keyword
declares a class attribute or method as static (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, you can use a variable to dynamically call a class. But the value of this variable cannot be the keywords self, parent or static.
Example
"; $foo = new Foo(); print $foo->staticValue() . "
"; ?>
Program running result:
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.
Example
An error will be reported when executing the following code:
Program running result:
Fatal error: Cannot override final method BaseClass::moreTesting() in D:\WWW\Basis\oop\opp_9.php on line 16
Call parent Class constructor method
PHP will not automatically call the constructor of the parent class in the constructor of the subclass. To execute the constructor of the parent class, you need to call parent::__construct()
Instance
"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); // 子类构造方法不能自动调用父类的构造方法 print "SubClass 类中构造方法" . "
"; } } class OtherSubClass extends BaseClass { // 继承 BaseClass 的构造方法 } // 调用 BaseClass 构造方法 $obj = new BaseClass(); // 调用 BaseClass、SubClass 构造方法 $obj = new SubClass(); // 调用 BaseClass 构造方法 $obj = new OtherSubClass(); ?>
# in the constructor of the subclass##Program running results:
Construction method in BaseClass classConstruction method in BaseClass class
Construction method in SubClass class
Construction method in BaseClass class