Home  >  Article  >  Backend Development  >  Detailed explanation of PHP object-oriented_PHP tutorial

Detailed explanation of PHP object-oriented_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:15:581112browse

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 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.

Object-oriented model

Object-oriented concept:
oop (object-oriented programming) can make its code more concise, easy to maintain and have stronger Reproducibility

What is a class:
A class is a collection of objects with the same properties and services. For example, people, books, ships, and cars all belong to classes. They do things for objects belonging to that class. In order to provide a unified abstract description, a class is a separate program in a programming language. It should have a class name that includes two parts: attribute description and service.
What is an object:
An object is an entity in the system that describes objective events. It is a basic unit that constitutes the system. *Data and code are bundled in an entity*. An object consists of a set of properties and a set of behaviors that operate on this set of properties.
From an abstract point of view, an object is an abstraction of something in the problem domain or implementation domain. It reflects the information saved and the role played by the thing in the system: it is a set of attributes and an encapsulation body that has the authority to operate on these attributes. The objective world is composed of objects and the connections between objects.
The relationship between classes and objects:
The relationship between classes and objects is like the relationship between molds and castings. The result of the strength of the class is the object, and the abstraction of the object is the class. A class describes a group of people with the same characteristics. (property) and objects with the same behavior.

Classes, attributes and methods

Definition of class syntax format in PHP:

Copy code The code is as follows:

class classname [optional attribute]{
public $property [=value];… //Use public to declare a public identifier and then give it to a variable. Variables can also be assigned values
function functionname (args){ //Member function in class method
code} ...
//Class method (member function)
}

Generate object ( Instantiation of class): $object name=new classname( );

Use the properties of the object

In a class, you can access a special pointer $this when When setting or accessing the variable through an operation in the class, use $this->name to reference.
Generation of the object
After defining the class, use a new to declare it. Due to the encapsulation characteristics of the object data, Objects cannot be directly accessed by the main program block. The properties and behavior functions defined in the class must be called through the object to indirectly achieve the purpose of accessing the data in the control class.
The relationship between objects and classes
The relationship between objects and classes:
Objects actually exist and occupy dynamic resources.
A class is a blueprint of an object and may occupy static resources.
Object attributes occupy dynamic resources
Class (static) attributes are actually "global variables" in the class namespace
Performance considerations:
Each object occupies separate data space
Increase The calling hierarchy may consume execution time
Parameter form and transfer method of method
Parameters of method can be basic data types, arrays and class objects.
Basic data type: Pass by value parameter
Array: Pass by value parameter
Class object: Pass by reference
Constructor
The constructor plays the role of initialization in the class
Constructor The generation method is the same as other functions except that its name must be __construct().
Syntax format:
function __construct(parameter){
. . . . . . . .
}
Example:
Copy code The code is as follows:

class Person{
public $name ;
public $sex;
public $age;
function __construct($name,$sex,$age){
echo "I am the constructor
";
$ this->name=$name;
$this->sex=$sex;
$this->age=$age;
}

Output results : Initialization

Destructor

When the object leaves its scope (for example, the function in which the object is located has been called), the system automatically executes the destructor. Memory should be released in the destructor before exiting.
Destructor__destruct The destructor does not have any parameters
Example:
Copy code The code is as follows:

class person{
function _ _destruct( )
{ echo "bye bye !"; }
}
$a=new person();

Access type
public public (public modifier) ​​can be accessed both inside and outside the class
private private (private modifier) ​​can only be accessed within the class
protected protected ( Protected member modifier) ​​Subclasses can access the outside of the class but cannot access

Three important features of oop

Encapsulation, inheritance, polymorphism
Encapsulation: Encapsulation is the combination of an object's properties and behaviors into an independent unit.
Encapsulating a class requires two steps. The first step is to privatize a class. The second step is to use set and get to read and assign values.
The advantage is that it hides the implementation details of the class and can easily add logic. Controllability, restricting unreasonable operations on attributes, making it easy to modify and enhance the maintainability of the code.

__get and __set
Generally speaking, it is more in line with realistic logic to make classes private.
Two predefined functions are used to obtain and store values.
__get Gets the value, usually the value of the domain
__set Sets the value, usually the value of the domain
__call When calling a method that does not exist in an object, an error will occur. call() is the method to handle this situation. .

Static properties and methods

static keyword to declare static methods
static static variable generates a static variable inside the class that can be used by all classes In other words, static members are placed in the "initialized static section", which is placed when the class is loaded for the first time, so that it can be shared by every object in the heap memory
Usage method: self:: $static property, self::static method
static function p(){
echo self::$country;
echo self::PI;//Access constants
//echo $this- >name;Only static properties can be operated in static methods
//self::p();
}
External calls: Class::$static properties, Class::static methods

const keyword: used to generate constants. Constants are the only convention constants that cannot be changed. Constants are uppercase.
const CONSTANT = 'constant value'; Generate a constant.
echo self::CONSTANT; // Class internal access
echo ClassName::CONSTANT;//External access to class

Inheritance

Objects of class B have all the attributes and behaviors of class A, and are called B Inheritance from class A.
If a class inherits properties and services from multiple classes, this is called multiple inheritance. Usually we call the inheriting class a subclass and the inherited class is a parent class. In PHP, there is only single inheritance, but a parent class can Inherited by multiple classes, but a subclass can only have one parent class, but associated inheritance is allowed, and the definition of the class can be reduced through inheritance.
extende declares inheritance relationship
Syntax format: class B extends A This example indicates that B inherits A
External access of the class is valid for subclasses
Attributes and methods of subclasses and parent classes
The subclass inherits all the contents of the parent class, but the private part in the parent class cannot be directly accessed
The newly added attributes and methods in the subclass are extensions of the parent class
What is defined in the subclass is the same as the parent class The attribute with the same name is an override of the parent class attribute, and the method with the same name is also an override of the parent class method

Overridden method

In the child class, use parent Access overridden properties and methods in the parent class

parent::__construce();
parent::$name;
parent::fun();

Override Original attributes of the parent class
clone clone object syntax format $c=clone $p; $c clone object $p output echo $c->name;

Object comparison
==== Two comparison operators.
== compares the contents of two objects.
=== is the handle of the comparison object, that is, the reference address.

The instanceof operator is used to detect whether the object belongs to a certain class. The type returns true if it does not belong.
__clone() If you want to change the content of the original object after cloning, you need to use __clone( )
function __clone(){
$this->name="I am a clone";
}

final means that a class is The final version means that it cannot be called by a subclass

Polymorphism

Polymorphism means that after the attributes or behaviors defined in the parent class are inherited by the subclass , can have different data types or exhibit different behavior. This allows the same property or behavior to have different semantics in the parent class and its various subclasses.
That is to say, the results of executing the same method in the subclass and the parent class are different.
Copy code The code is as follows:

class A {
function info(){
echo "A INFO ";
}
}
class B extends A {
function info(){
echo "B INFO";
}
}
class C extends A {
function info(){
echo "C INFO";
}
}
function printinfo($obj){
function printinfo(A $obj){
if($obj instanceof A)
$obj->info();
$obj->info();
}
}
$a=new A(); $b=new B(); $c=new C();
printinfo($a); //Output A INFO
printinfo($b); //Output B INFO
printinfo($ c); //Output C INFO


Abstract method and abstract class

Abstract method is used as a template for subclasses.
Copy code The code is as follows:

abstract class Person{
public $name;
abstract function getInfo();
}

Abstract classes cannot be used in an abstract class , there must be an abstract method. But dynamic functions can be defined in abstract classes.
Interface
When a class inherits an interface, it must override all methods of the interface. Interfaces can only declare constants. Interface methods must be defined as shared otherwise they cannot be inherited. Interfaces can inherit from multiple interfaces
Syntax:
Copy code The code is as follows:

interface PCI{
const TYPE="PCI";
//public $name; error
function start();
function stop();
}

Methods in the interface can be declared static
Copy code The code is as follows:

interface A{ function a();}
interface B{ function b();}
interface C extends A{ function c();}
class D implements B,C{
function a(){}
function b(){}
function c(){}
}

Class
Class declaration:
Copy code The code is as follows:

Permission modifier class class name { //Permission monk symbol: public, protected, private or omit 3.
//Class body; //class It is the class creation keyword
  }        //The class name must follow class, and the members of the class must be placed between {}.{}.
 ?>
//ps: in the class key In addition to permission modifiers, you can also add static, abstract and other keywords before the word. A class, that is, all the content between a pair of curly brackets must be in a piece of code, and the content in the class is not allowed to be divided into pairs. block.
class ConnDB{
   //....
?> 🎜>?>



Member attributes:
Variables declared directly in the class are called member attributes/variables. Their types can be scalar types in PHP and For composite types, it is invalid to use resource types and empty types.
In addition, when declaring member attributes, they must be modified with keywords: keywords with specific meanings: public, protected, private; no specific meanings are required: var. When declaring member properties, there is no need to assign an initial value.
Member constant:


Modified with const constant, for example: const PI = 3.1415926; Constant The output does not need to be instantiated, it can be called directly by class name + constant name, the format is: class name::constant name
ps. Special access methods:--------"$this" and "::"
1) $"this" exists in each member method. It is a special object to use methods. The member method belongs to that object, and $this application represents that object, and its function is to specifically complete Access between internal members of the object.
2) "::" becomes the scope operator. Use this operator to call constants, variables and methods in the class without creating an object. Its syntax format is as follows:

Keywords:: variable name/constant name/method name

Keyword: parent, you can call member variables, member methods and constants in parent class members;
self, you can Call static members and constants in the current class;
Class name, you can call constants, variables and methods in the class;


Member methods:


In the class The function declared in becomes a member method. Multiple functions can be declared in a class, that is, the object can have multiple member methods. The declaration of member methods is the same as the declaration of functions. The only special thing is that member methods can have keywords for them. Modify it to control its access rights. Instantiation of class

Create object:


 $Variable name = new class name ([parameter]); //Instantiation of the class. Accessing class members:
 $Variable name-> Member attribute = value;
Constructor and destructor method
The constructor is the first one after the object is created The method automatically called by the Bai object. It exists in the declaration of each class and is a special member method, generally used to complete some initialization operations. If there is no constructor in the class, the system will automatically generate a constructor without parameters by default.
 Format:



Copy code
The code is as follows: function _construct(formal parameter list){    // Method body
 };


The destructor method is the opposite of the constructor method. It is the last method called before the object is destroyed. It will complete a specific operation, such as closing the file and Release memory.
Format:


Copy code
The code is as follows:

function _destruct(){
   ///Method body
  };

Object-oriented features: encapsulation, abstraction, polymorphism.
Encapsulation:
Combining the member properties and methods in the class into an independent and identical unit, and hiding the content details of the object as much as possible. The purpose is to ensure that parts outside the class cannot access the class at will Internal data (member properties and member methods), thereby avoiding the impact of external errors on internal data.
Class encapsulation is achieved through the keywords public, private, protected, static and final. Please see php for the functions of each keyword. Related documents.
Inheritance:
Make a class inherit and have the member properties and member methods of another existing class, where the inherited class becomes the parent class and the inherited class becomes Subclass. Through inheritance, code reusability and maintainability can be improved. Class inheritance uses the extends keyword.
Format:
Copy code Code As follows:

class subclass name extends parent class name {
    //Subclass method body.
  }

Also passed the parent:: keyword You can call the member methods of the parent class in the subclass method. The format is as follows:
 parent::Member method of the parent class (parameters);

Override the method of the parent class:

The so-called method of overriding the parent class is to use the method in the subclass to replace the method inherited from the parent class, which is also called the rewriting of the method. The key to rewriting is to create the same method as the parent class in the subclass. The same method in the class, including method name, parameters and return type.

Polymorphism:
Polymorphism refers to the ability of a program to handle multiple types of objects .php polymorphism has two implementation methods, namely polymorphism through inheritance and polymorphism through interfaces.
Polymorphism is achieved through inheritance, that is, by overriding inherited member methods to achieve polymorphic effects.
Copy code The code is as follows:


abstract class ParentClass{
abstract function printMessage( );
}
class SubClassA extends ParentClass{
function printMessage(){
echo "i am message from class A";
}
}
class SubClassB extends ParentClass {
function printMessage(){
echo "i am message from class B";
}
}
function printMSG($object){
if( $object instanceof ParentClass) {
$object->printMessage();
}else{
echo "error!";
}
}
$objectA=new SubClassA();
printMSG($objectA);
$objectB=new SubClassB();
printMSG($objectB);
?>

Polymorphism is achieved through interfaces, by defining interfaces , with an empty method. Then the class inherits the interface.
Copy the code The code is as follows:


interface interfaceInfo{
function printMessage();
}
class ClassA implements interfaceInfo{
function printMessage(){
echo "message form class A";
}
}
class ClassB implements interfaceInfo{
function printMessage(){
echo "message form class B";
}
}
function printMSG($object){
if($object instanceof interfaceInfo){
$object -> printMessage();
}else{
echo "error !";
}
}
$objectA =new ClassA();
printMSG($objectA);
$objectB =new ClassB();
printMSG($objectB);
?>

ps. Abstract classes and interfaces.
Abstract classes and interfaces are special classes that cannot be instantiated. They can be used with object-oriented polymorphism.
Abstract classes:
Abstract classes are a type of class that cannot be instantiated. Instantiated classes can only be used as parent classes of other classes. Abstract classes are declared using the abstract keyword, and their format is as follows:
Copy code Code As follows:

abstract class abstract class name {
 Abstract function member method (parameter); //
 }

Abstract classes are similar to ordinary classes, including member variables and member methods. The difference between the two is that an abstract class must contain at least one abstract method. Abstract methods have no method bodies, and the implementation of their functions can only be completed in subclasses. Abstract methods Also use the keyword abstract to modify.

Interface:
The inheritance feature simplifies the creation of objects and classes and enhances the reusability of code. However, PHP only supports single inheritance. If you want to implement multiple inheritance, you must use an interface.
Declaration of the interface: This is achieved through the interface keyword. The methods declared in the interface must be abstract methods. Variables cannot be declared in the interface. They can only be declared as constants using the const keyword. member attributes, and all members in the interface must have puclic access rights. The ainterface declaration interface format is as follows:
Copy code The code is as follows:

inerface interface name {
//Constant members; //Members can only be constants.
//Abstract method;
}

Because the interface cannot be implemented The instantiation operation can only be implemented in the form of subclass inheritance interface. The implementation format is:
Copy code The code is as follows:

Class subclass name implements interface name 1[, interface name 2, interface name 3,...]{
  // Subclass method body.
}

Commonly used keywords:
1) final: final means final, final. This means that classes and methods modified by the final keyword are final versions and cannot be Inheritance and cannot have subclasses. It cannot be overridden or overridden.
 2) static: Member properties and member methods modified by the static keyword are called static properties and static methods. Static member properties and methods do not require It can be used directly after being instantiated.
Static attribute: It belongs to the class itself, not to any instance of the class. It is equivalent to a global variable stored in the class and can be accessed through the class at any location. The access format is :
  Class name::$static property name;
  If you want to access static properties in member methods inside the class, then add the operator: "self::" before the name of the static property.
Static method: Since it is not subject to any object restrictions, you can directly reference the static method in the class without instantiating the class. The reference format is as follows:
Class name:: Static method name (parameters);
If you want to call a static method in a member method inside the class, then add the operator: "self::" before the name of the static method. Only static variables can be called in static methods, not ordinary variables. Variables; static variables can be called in ordinary methods.
In addition to not requiring instantiation, using static members also has another effect: after the object is destroyed, the modified static data is still retained for the next call.
3) clone. Cloning of objects can be achieved through keywords. The use of clone objects has no relationship with the original objects, that is, the cloned objects will re-apply for a storage space to store the contents of the original objects. The format is as follows:
 $Clone object = clone $Name of the original cloned object;
After the cloning is successful, their n member methods, attributes and values ​​are completely equal. If you want to re-initialize the copy, you need to use _clone().
Magic method _clone () can reinitialize the cloned copy object. It does not require any parameters, and it automatically contains references to the $this (copy object) and $that (original object) objects.
Comparison of objects:
 "= =" means comparing the contents of two objects, "===" means comparing the reference addresses of two objects for equality.
Object type detection: The instanceof operator can detect which object the current object belongs to.

Object-oriented---common magic methods:
The common magic methods we have learned above are: _construct(), _destruct(), _clone. Below we will introduce several common magic methods.
_get(),_set();
The above two methods are used to copy or obtain values ​​of private members.
_set() sets the value for private member attributes while the program is running. No return value is required. The _set() method includes two parameters that cannot be omitted: variable name and variable value. This method does not need to be actively called, and the private keyword can be added to the method.
 _get(): When the program is running , obtain the value of the private member's attribute outside the object. It has one parameter: the name of the private member attribute. It returns a value that allows the object to be used externally. This method is also not allowed to be called actively.

_isset( ),_unset():
The isset() function is used to detect whether a variable exists. In object-oriented, public member attributes can be detected through the isset() function, but for private member attributes, this function cannot Function. Therefore, the _isset() function was created to play this role. The format is as follows:
bool _isset(string name);
_unset() is also used to delete the specified variables and private member attributes of the object. The format is as follows:
void _unset(string name);//
_call():
The function of the _call() method is that when the program tries to call a non-existent or invisible member method, PHP will first Call the _call() method to store the method name and its parameters (method name and method parameters). The method parameters exist in the form of an array.
_toString() method:
Its function is to use echo or print output When outputting an object, convert the object into a string.
If there is no _toString() method, a fatal error will occur when outputting the object directly.
When outputting the object, it should be noted that the echo or print statement is directly followed by the Do not add extra characters in the middle of the output object, otherwise _toSting() will not be executed.
_autoload() method:
Save an independent, complete class to a php page, and file Keeping the name and class name consistent is a good habit that every developer needs to develop. This way, you can easily find it the next time you use it. But there is a situation: if you want to introduce many classes into a page, You need to use the include_once() function or require_once() function to introduce them one by one. The _autoload() method introduced in php5 can automatically instantiate the classes that need to be used. When a class has not been instantiated, _autoload() will automatically go to the specified Automatically search for files with the same class name under the path. If found, continue execution, otherwise an error will be reported.
Copy code The code is as follows:


function _autoload($class_name){
$class_path = $class_name.'.class.php';
if(file_exists($class_path)) {
   include_once($class_path);
  }else{
  echo 'The class does not exist or the class path is wrong'; / will be loaded automatically.
echo $class; //Output class content. If the _toString() method is customized, the content defined in _toString() will be output.
?>



http://www.bkjia.com/PHPjc/326008.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326008.htmlTechArticleThe main three characteristics of an object are the behavior of the object: what operations can be applied to the object, turning the light on and off is the behavior . The shape of the object: how the object responds when those methods are applied, color...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn