PHP Object-Oriented programming
Object-oriented program programming (object Oriented programming)
First, the concept of object-oriented programming
PHP introduces an object-oriented design method that "encapsulates" the data and the corresponding function that processes the data into a "class". An instance of a class is called an "object." Within an object, only functions that belong to that object can access the object's data.
Object-oriented programming has three main features: encapsulation, inheritance, and polymorphism.
1. Encapsulation
Encapsulation is the bundling of data and code together to avoid external distractions and uncertainties. In PHP, encapsulation is implemented through classes. A class is an implementation of an abstract data type, where all objects of a class have the same data structure and share the same code that implements the operation, and each object has its own state, that is, private storage. Thus, a class is a combination of the common behavior and the different states of all objects.
An object created by a particular class is called an instance of this class, so a class is an abstraction and description of an object, which is a uniform description of several objects that have a common behavior. Class also contains concrete methods for generating objects.
2. Inheritance
class provides a way to create a new class, and with the help of "inheritance", this important mechanism extends the definition of the class and realizes the superiority of object-oriented.
Inheritance provides a way to create a new class: A new class can be modified or expanded to meet the needs of the new class. The new class shares the behavior of an existing class, but it also has the modified or extra added behavior. Therefore, it can be said that the essential feature of inheritance is behavior sharing.
The new class that inherits the definition from a class inherits all the methods and properties of the existing class, and can add new methods and properties that are required. The new class is called a subclass of an existing class, and an existing class is called a parent class or a base class.
3. polymorphic
Different classes have different behaviors for different operations, called polymorphism. The polymorphic mechanism enables objects with different internal structures to share the same external interface, reducing the responsibility of the code in this way.
Ii. creating classes, properties, and methods in PHP
Class is the core of object-oriented programming, which is a data type. A class consists of variables and functions, in which variables are called attributes or member variables, and functions are called methods. The syntax format for defining a class is as follows:
Class classname{[var $property [=value]; [function functionname ($args) {//code}]}
In PHP, classes need to be defined using the class keyword, followed by the name classname. The naming convention for a class conforms to the naming rules for PHP tags and cannot be a reserved word for PHP. The class name is followed by a pair of curly braces, and the curly braces contain the properties and methods of the class.
In the class, use the keyword var to declare the variable, which is the property of the class. Use the keyword function to define functions, which are methods of classes.
Note: When defining a property, the value assigned to the attribute cannot use a delimiter, cannot be an expression, cannot contain parentheses, and cannot be assigned a value by another variable. In addition, variables inside a class's methods are just ordinary variables, not attributes of the class, because the scope of the method is limited to the inside of the method. You cannot put the definition of a class into multiple files or multiple PHP blocks.
Iii. instantiation and access of classes
After declaring a class, the class exists only in the file, and the program cannot be called. Before a program can be used to create an object, the process of creating a class object is called instantiation of the class. The instantiation of the class uses the new keyword, which is followed by specifying the class name to instantiate.
In a class, you can access a special pointer "$this". If the current class has an attribute $attribute, you can use "$this->attribute" to refer to it when you want to access the property inside the class.
After the object is created, you can access the properties and methods of the object outside of the class, accessing the object by using the "-and" compliance plus the properties and methods you want to access. Note there is no "$" in front of the property.
Description: Some classes have access control over properties in a class, and direct access will cause an error if the properties in the class cannot be accessed outside the class set.
Four, class of access control
In PHP5, the access modifier public, private, and protected, which control the visibility of properties and methods, are typically placed before the declarations of properties and methods.
①public. Properties and methods that are declared as public can be accessed outside or inside the class. Public is the default option and will be public if no modifiers have been developed for a property or method.
②private. Properties and methods declared as private can only be accessed inside the class, and private properties and methods will not be inherited.
③protected. Properties and methods that are declared as protected can be accessed only within the class and within the child class.
When you are designing a class, you typically set the properties of the class to private, and most of the methods are public. In this way, code other than the class cannot directly access the private data of the class, thereby encapsulating the data, while the public method provides an external interface for the internal private data, but the details of the implementation of the interface are not visible outside the class.
V. Static properties and Methods
The so-called "static" means that the defined properties and methods are independent of the instance of the class and are related only to the class itself. Static properties and methods are typically used to contain the data and functionality that the class will encapsulate and can be shared by instances of all classes. Static properties and methods can be defined in a class using the static keyword.
Access to static properties and methods requires the use of the range resolver "::", in the following format:
ClassName:: $attribute; accessing static properties
Classname::cfunction ([$args,...]) Accessing static methods
Note: Only static properties and methods can use range resolvers, and non-static properties and methods cannot be accessed using the scope resolver.
Vi. Constructors and destructors
A constructor is a special function in a class, and when an instance of a class is created, the constructor is automatically called, and the main function is usually to initialize the objects in the class. In contrast to constructors, destructors are called automatically when objects of a class are destroyed.
① the constructor function. In PHP5, the name of the constructor is "__construct", and "Contruct" is preceded by two underscores. If a class has both a __contruct constructor and a function with the same class name, PHP5 will consider __construct as a constructor. Constructors in PHP can have parameters, or they can be without parameters.
② the destructor. The name of the destructor for the class is __destruct, and if the __destruct function is declared in the class, PHP will call the destructor to destroy the object from memory before the object is destroyed, saving the server resources.
If you have parameters in the constructor, you can also specify parameters for the constructor after the class name when you create the object.
Vii. Inheritance of Classes
1. Subclass access to Parent class
In PHP, it is possible to invoke methods that are already defined in these classes by inheriting other classes, and PHP does not support multiple inheritance, so a subclass can inherit only one parent class. You can use the extends keyword to indicate the relationship between a class and a class.
Class B inherits from Class A, so objects of Class B can access the properties and methods of Class A, but the properties and methods of private in a cannot be inherited, the properties and methods of protected in a can only be accessed inside B, objects created by Class B cannot be accessed, or an error will result. B is a subclass of a, has the same data and functions as Class A, and B can also declare its own properties and methods.
Inheritance is single-directional, subclasses can inherit attributes from the parent class, but the parent class cannot inherit attributes from subclasses.
If the subclass does not have its own constructor, the subclass automatically invokes the constructor of the parent class when it is instantiated. If the subclass has its own constructor, it executes its own constructor.
If you want to call a method of a parent class in a subclass, you can use the parent keyword with a range resolver, such as "Parent::functionname ()", in addition to $this. The latter method is recommended because the preceding method is prone to confusing the structure of subclasses and parent methods. The properties of the parent class can only be accessed by using "$this-to" in the subclass, which is not distinguished from the parent class and subclass.
Inheritance can be multiple. For example, Class B Inherits Class A, Class C inherits Class B, and Class C inherits all the attributes of the parent class of Class A and Class B.
2. Overloading
Overloading of methods refers to the ability to define multiple methods with the same name in a class, distinguishing them by the number and type of arguments. In PHP, it is possible to implement a method that resembles a method overload by inheriting from the class and defining the same name in the child class as the parent class.
3. Use the final keyword
The final keyword in PHP, which is used when declaring a class, will not allow the class to be inherited. In addition, if the final keyword is used to declare a method in a class, the method cannot be overloaded in any subclasses.
Note: The final keyword can only be used to declare classes and methods.
VIII. abstract classes and interfaces
1. Abstract class
An abstract class is a special class that is defined using the keyword abstract and cannot be instantiated. An abstract class contains at least one abstract method, which is also defined by the abstract keyword. The abstract method provides only the declaration of the method and does not provide an implementation of the method. For example:
Abstract function func ($name, $number);
The class that contains the abstract method must be an abstract class.
Abstract classes cannot be used to create objects, so they can only be used by inheritance. Inheriting the subclass of an abstract class, you must overload all abstract methods in the abstract class to be instantiated.
2. Interface
PHP can only provide single inheritance, that is, a class can have only one parent class. An interface is a special abstract class that is defined by replacing the class keyword with the interface keyword. Non-abstract methods and properties are allowed in abstract classes, whereas methods defined in interfaces are abstract methods. You cannot use attributes in an interface, but you can use constants defined by the Const keyword. For example:
Const con= "Tom";
Interfaces are defined in a similar way to defining classes, and the abstract keyword is not applicable in an interface.
Note: All methods in an interface require the public definition, which can be omitted because the default access modifier is public.
interfaces, like classes, also support inheritance, and inheritance between interfaces uses the extends keyword. For example:
<?phpinterface a{const Name= ""; function Show ();} Interface B extends a{function getname ();}? >
An interface can be instantiated after it has been defined, and an instantiation of the interface is called an implementation of the interface. To implement an interface requires a subclass to implement all the abstract methods of the interface. Subclasses that define an interface use the Implements keyword, and a subclass can implement multiple interfaces, which solves the problem of multiple inheritance.
A subclass can also inherit one parent class and multiple interfaces at the same time.
Nine, the Magic method of the class
PHP stipulates that the method that starts with two underscore "__" is reserved as a magic method, so try not to start with "__" when defining a function name, unless you are trying to reload an existing magic method.
1. Cloning objects
PHP uses the Clone keyword to create an object that has the same properties and methods as the original object, which is used in cases where an object of two classes is instantiated through a class. For example:
$new _obj=clone $old _obj;
$new _obj is the new object name, $old _obj is the name of the object to be cloned.
The cloned object has all the properties of the cloned object, and if you need to change these properties, you can use the Magic method provided by PHP __clone. This method is automatically called when cloning an object, similar to the __construct and __destruct methods. In the __clone method, you can define the exact replication behavior or perform some operations.
2. Method overloading
PHP5 has a magic method __call, which can be used to implement overloading of methods. The __call method must have two parameters. The first parameter contains the called method name, and the second parameter contains the array of arguments passed to the method. The __call method is called when a method in a class is accessed.
3. Accessing the properties of a class
Typically, accessing the properties of a class directly from outside the class is not a recommended method. You can then use the __get and __set methods to examine and set the value of the property so that encapsulation can be achieved.
4. String conversions
If you want to output an object, you can define a __tostring method in the class that returns an output-capable string in the method.
5. Loading objects automatically
The __autoload method is used to automatically load an object, which is not a class method, but a separate function. If the __autoload function is defined in the script, when an undeclared class is instantiated with the New keyword, the name of the class is passed as a parameter to the __autoload function, and the __autoload function automatically contains the file with the class based on the parameter and loads the class with the same name in the class file.
6. Serialization of objects
Object serialization refers to converting an object into a byte stream, transferring the serialized object to a file or network, and then deserializing it back to the original data. Object serialization uses the Serialize () function, which deserializes the unserialize () function. In the case of object serialization, if there is a magic method __sleep,php calls the __sleep method, which is mainly used to clear the work such as data submission, closing the database link, and returns an array that contains all the variables that need to be serialized; After deserializing an object, PHP calls __ The Wakeup method is primarily used to reconstruct lost resources when the object is serialized. Neither of the two magic methods takes parameters.
Ten, the judgment of the instance type
When the system is large, it is often necessary to determine whether an object is created by a class. This can be accomplished using the INSTANCEOF keyword. The instanceof keyword can examine the type of an object, determine whether an object is an instance of a particular class, inherit from a class, or implement an interface. Use the following:
$var instanceof class_name;
Returns true if the variable $var is the object created by the class class_name, otherwise returns false.
This article is from the "Rangers" blog, please be sure to keep this source http://ccnupxz.blog.51cto.com/8803964/1840641
A brief introduction to object-oriented programming in PHP