Home  >  Article  >  Backend Development  >  php object-oriented (basic)_PHP tutorial

php object-oriented (basic)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:37:24784browse

I recently re-learned the object-oriented part of PHP. I took some notes and shared them with you. Part of them is my introduction. The colored parts are generally the areas that I think are more important or need attention. I want to share them with you. I hope you will Give more opinions and learn together. 1. Destructor: __destruct () //This is a destructor, called before the object is destroyed
function __destruct()
{
echo “Goodbye”.$this->name.”
”;
}

2. Constructor: __construct()

Can a PHP subclass inherit the constructor method of the parent class?
If there is no subclass constructor defined, the parent class constructor will be called by default. If the constructor of a subclass is defined, then call itself directly
function __construct($name, $sex, $age)
{
//The $name passed in through the construction method assigns an initial value to the member attribute $this->name
$this->name=$name;
//The $sex passed in through the constructor is assigned an initial value to the member attribute $this->sex
$this->sex=$sex;
//The $age passed in through the constructor is assigned an initial value to the member attribute $this->age
$this->age=$age;
}

3. __set() sets attributes. __get() gets attributes class Person
{
//The following are the member attributes of people, which are all encapsulated private members
private $name; //Person’s name
private $sex; //Person’s gender
private $age; //Age of person
//__get() method is used to obtain private attributes
private function __get($property_name)
{
echo "When directly obtaining the private attribute value, this __get() method is automatically called
";
if(isset($this->$property_name))
{
return($this->$property_name); //After removing it, member variables cannot be correctly assigned
}
else
{
return(NULL);
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value)
{
echo "When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
";
$this->$property_name = $value;
}
}
$p1=new Person(); //If you directly assign a value to a private attribute, the __set() method will be automatically called to assign the value. $p1->name="Zhang San"; $p1->sex="Male"; $p1->age=20; //To directly obtain the value of a private attribute, the __get() method will be automatically called to return the value of the member attribute. echo "Name:".$p1->name."
"; echo "Gender:".$p1->sex."
"; echo "Age:".$p1->age."
"; ?>
Program execution result: When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute. When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute. When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute. When directly obtaining the private attribute value, the __get() method is automatically called. Name: Zhang San When directly obtaining the private attribute value, the __get() method is automatically called. Gender: Male When directly obtaining the private attribute value, the __get() method is automatically called. Age:20
If the above code does not add the __get() and __set() methods, the program will go wrong, because private members cannot be operated outside the class. The above code helps us directly access the encapsulated private members by automatically calling the __get() and __set() methods.


4. __isset() method, __unset() method
class Person
{
//The following are the member attributes of the person
private $name; //person's name
private $sex; //Person’s gender
private $age; //Age of person
//__get() method is used to obtain private attributes
private function __get($property_name)
{
if(isset($this->$property_name))
{
return($this->$property_name);
}else {
return(NULL);
}
}
//__set() method is used to set private properties
private function __set($property_name, $value)
{
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm)
{
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm)
{
echo "Automatically called when the unset() function is used outside the class to delete private members
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true.
echo var_dump(isset($p1->name))."
";
echo $p1->name."
";
//When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute.
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>
The output is: The isset() function is automatically called when measuring private members. bool(true) this is a person name Automatically called when the unset() function is used outside the class to delete a private member. __set(), __get(), __isset(), __unset() These four methods are all added to the object and will be automatically called when needed. Used to complete operations on private properties inside the object outside the object.


5. Call the parent class interface
header("Content-Type: text/html; charset=utf-8");
class Person
{
//The following are the member attributes of people, which are all encapsulated private members
private $name; //Person’s name
private $sex; //Person’s gender
public $age; //Age of person


function __construct($name, $sex, $age)
{
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}

function say(){
echo "My name is:".$this->name."Gender:".$this->sex."Age:".$this->age;
}


}


class Student extends Person
{
var $school; //Attributes of the school where the student is located
function __construct($name, $sex, $age,$school)
{
parent::__construct($name,$sex,$age);
$this->school=$school;
}


//This method for students to learn
function study()
{
echo "My name is:".$this->name." I am studying at ".$this->school."
";
}
//This is a method that can be learned and talked about. It describes all its attributes and covers the method of the same name of the parent class
function say()
{
//Use the "class name::" of the parent class to call the overridden method in the parent class;
// Person::say();
//Or use "parent::" method to call the overridden method in the parent class;


parent::say();
//Add some of your own functions
echo "My age is:".$this->age."I go to school in ".$this->school."
";
}
}
$p1 = new Student("wangyaofeng","Male","22","Henan University of Science and Technology");
$p1->say();

?> result: My name is: wangyaofeng Gender: Male Age: 22 My age is: 22 I study at Henan University of Science and Technology


6. Application of final keyword
This keyword can only be used to define classes and methods. You cannot use the final keyword to define member properties because final means constant. We use the define() function to define constants in PHP, so we cannot use final to define them. Member properties. Classes marked with the final key cannot be inherited; code snippet final class Person { ... } class Student extends Person { } The following error will occur: Fatal error: Class Student may not inherit from final class (Person) Methods marked with the final key cannot be overridden by subclasses and are the final version; code snippet class Person {
final function say()
{
}
} class Student extends Person {
function say()
{
}
} The following error will occur: Fatal error: Cannot override final method Person::say()

7.Use of static and const keywords
The Static keyword describes the member attributes and member methods in the class as static; what are the benefits of static members? Earlier we declared the human being of "Person". In the "Person" class, if we add a "person to which Country" attribute, in this way, use the "Person" class to instantiate hundreds or more instance objects, and each object will have the attribute of "country to which it belongs". If the project developed is for the Chinese , then each object has a country attribute that is "China" and other attributes are different. If we make the "country" attribute a static member, then there will be only one country attribute in the memory. And let these hundreds or more objects share this attribute, static Members can restrict external access, because static members belong to the class and do not belong to any object instance. They are space allocated when the class is loaded for the first time. Others The class is inaccessible and is only shared with instances of the class, which can protect the members of the class to a certain extent .Let's analyze it from the perspective of memory. The memory is logically divided into four segments. The objects are placed in "heap memory", the references of the objects are placed in "stack memory", and the static members are placed in "initialization". "Static section" is placed when the class is loaded for the first time and can be shared by every object in the heap memory, as shown below; the static variables of the class are very similar to global variables and can be shared by all instances of the class. The same goes for static methods of classes, similar to global functions.
class Person
{
//The following are the static member attributes of people
public static $myCountry="China";
// var $name; //The person’s name
//This is a static member method of people
public static function say()
{
echo "I am Chinese
";
}
}
//Output static properties
echo Person::$myCountry;
//Access static method
Person::say();
//Reassign static properties
Person::$myCountry="United States";
echo Person::$myCountry;
?> Because static members are created when the class is loaded for the first time , there is no need for objects outside the class and just use the class name
To access static members; as mentioned above, static members are shared by each instance object of this class, then we use the object
Can I access static members in a class? From the picture above, we can see that static members do not exist inside every object
Yes, but every object can be shared, so if we use objects to access members, there will be no such attribute definition,
Static members cannot be accessed using objects. In other object-oriented languages, such as Java, you can access them using objects
Asking about static members, if you can use objects to access static members in PHP, we should try not to use them because static
When we are working on a project, our purpose is to access members using class names (Person::$myCountry="United States";).
Static methods in a class can only access static properties of the class. Static methods in a class cannot access non-static members of the class
,The reason is very simple. If we want to access other members of this class in the method of this class, we need to use the $this reference,
The reference pointer $this represents the object that calls this method. As we said, static methods are not called with objects, but with
Use the class name to access, so there is no object at all, and there is no $this reference. Without the $this reference,
Non-static members in a class cannot be accessed, and because static members in a class can be accessed without objects,
in the class Static methods can only access static properties of the class. Since $this does not exist, we use
to access other static members in the static method. Is a special class "self"; self is similar to $this, except that self represents the class where this static method is located. So
In a static method, you can use the "class name" of the class where the method is located
, you can also use "self" to access other static members,
If there are no special circumstances, we usually use the latter, that is, the "self::member attribute" method.
Code snippet

class Person
{
//The following are the static member attributes of people
public static $myCountry="China";
//This is a human static member method, access other static members through self
public static function say()
{
echo "I am".self::$myCountry."
";
}
}
//Access static method
Person::say();
?>
Can static members be accessed in non-static methods? Of course it is possible, but "$this" reference cannot be used
Also use the class name or "self::member attribute form".

const is a keyword that defines constants. To define constants in PHP, you use the "define()" function. But when defining constants in a class, the keyword "const" is used. Similar to #define in C. If its value is changed in the program,
Then an error will occur. The access method of member attributes modified with "const" is different from the access method of members modified with "static"
Not much, just use the "class name" and the "self" keyword in the method. But you don’t need to use the “$” symbol, nor can you use
Use objects to access.
Code snippet
classMyClass
{
//Define a constant constant
const constant = 'constant value';
function showConstant() {
echo self::constant . "n"; //Use self to access, do not add "$"
}
}
echo MyClass::constant . "n"; //Use the class name to access without adding "$"
$class = new MyClass();
$class->showConstant();
// echo $class::constant; is not allowed
?>

8.__toString() method

We mentioned earlier that the method of declaring a method name starting with "--" in a class (provided to us by PHP) is done at a certain moment
Methods are automatically called and executed under different circumstances. The "__toString()" method is also automatically called. It directly outputs the
It is automatically called when the object is referenced. As we said before, the object reference is a pointer. For example: in "$p=new Person()", $p
It is just a reference. We cannot use echo to directly output $p, which will output "Catchable fatal error: Object of
"class Person could not be converted to string" error, if you define
in the class The "__toString()" method, when directly outputting the object reference, will not generate an error, but will be automatically called
The "__toString()" method outputs the characters returned in the "__toString()" method, so the "__toString()" method one
There must be a return value (return statement). Code snippet
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
//Define a __toString method and return a member attribute $foo
public function __toString() {
return $this->foo;
}
}
$class = new TestClass('Hello');
//Directly output the object
echo $class;
?>
The output of the above example:Hello
9. Clone objects
Sometimes we need to use two or more identical objects in a project. If you use the "new" keyword
If you re-create the object and assign the same attributes, it is more cumbersome and error-prone, so you need to base it on an object
It is very necessary to completely clone an identical object, and after cloning, the two objects will not interfere with each other.
In PHP5 we use the "clone" keyword to clone objects;
Code snippet

class Person
{
//The following are the member attributes of the person
var $name; //Person’s name
var $sex; //person’s gender
var $age; //Age of person
//Define a constructor parameter to assign values ​​to the attributes name $name, gender $sex and age $age
function __construct($name="", $sex="", $age="")
{
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//The way this person can speak, tell his own attributes
function say()
{
echo "My name is:".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}
}
$p1=new Person("Zhang San", "Male", 20);
//Use "clone" to clone the new object p2, which has the same properties and methods as the p1 object.
$p2=clone $p1;
$p2->say();
?>
PHP5 defines a special method name "__clone()" method, which is automatically called when an object is cloned. Use
The "__clone()" method will create an object with the same properties and methods as the original object. If you want to change the original object after cloning
content, you need to rewrite the original attributes and methods in __clone(),
The "__clone()" method can have no parameters, it automatically includes
Contains two pointers $this and $that , $this points to the copy, and $that points to the original;
Code snippet
class Person
{
//The following are the member attributes of the person
var $name; //Person’s name
var $sex; //person’s gender
var $age; //Age of person
//Define a constructor parameter to assign values ​​to the attributes name $name, gender $sex and age $age
function __construct($name="", $sex="", $age="")
{
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//The way this person can speak, tell his own attributes
function say()
{
echo "My name is:".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}
//Method automatically called when an object is cloned. If you want to change the contents of the original object after cloning, you need to rewrite the original attributes and methods in __clone()
function __clone()
{
//$this refers to the copy p2, and $that points to the original p1, so in this method, the properties of the copy are changed.
$this->name="I am fake $that->name";
$this->age=30;
}

}
$p1=new Person("Zhang San", "Male", 20);
$p2=clone $p1;
$p1->say();
$p2->say();
?>
The output of the above example:
Execution results
My name is: Zhang San Gender: Male My age is: 20
My name is: I am the fake Zhang San Gender: Male My age is: 30


10.__call handles calling errors
In program development, if when using an object to call an internal method of the object, the called method does not exist, then the program will
An error occurs, and then the program exits and cannot continue execution. So can we be prompted when the program calls a method that does not exist within the object
The called method and the parameters used do not exist, but the program can continue to execute. At this time, we have to use
that does not exist in the call. The method "__call()" is automatically called when the method is used.Code snippet
//This is a test class, there are no attributes and methods in it
class Test
{
}
//Generate an object of Test class
$test=new Test();
//Call a method that does not exist in the object
$test->demo("one", "two", "three");//This method does not exist
//The program will not execute here
echo "this is a test
";
?>
The following error occurred in the above example, and the program cannot continue to execute;
Fatal error: Call to undefined method Test::demo()
Next we add the "__call()" method. This method has 2 parameters. The first parameter is the process of calling a method that does not exist,
When the __call() method is automatically called, the non-existent method name is passed to the first parameter, and the second parameter is the method name
The parameters are passed in as an array.
//This is a test class, there are no attributes and methods in it
class Test
{
//Method that is automatically called when calling a non-existing method. The first parameter is the method name, and the second parameter is the array parameter.
function __call($function_name, $args)
{
print "The function you called: $function_name(parameters:";
print_r($args);
print ") does not exist!
n";
}
}
//Generate an object of Test class
$test=new Test();
//Call a method that does not exist in the object
$test->demo("one", "two", "three");
//The program will not exit and can be executed here
echo "this is a test
";
?>
The output result of the above example is:
Execution results
The function you called: demo (parameter: Array ( [0] => one [1] => two [2] => three ) ) does not exist!
this is a test.
11. Abstract methods and abstract classes In OOP language, a class can have one or more subclasses, and each class has at least one public method as external code
access its interface. Abstract methods are introduced to facilitate inheritance. Let’s first take a look at the definitions of abstract classes and abstract methods
Explain its use again.
What is an abstract method? The method we define in a class without a method body is an abstract method,
The so-called no method body refers to,
There are no curly braces and their contents when declaring the method,
Instead, add a semicolon after the method name directly when declaring it,
In addition, when declaring an abstract method, add a keyword "abstract" to modify it;
For example:
abstract function fun1();
abstract function fun2();
The above example is the abstract methods "fun1()" and "fun2()" without a method body modified by "abstract"
, don’t forget that there is a semicolon after the abstract method; so what is an abstract class? As long as one method in a class is an abstract method, then this
Each class must be defined as an abstract class, and the abstract class must also be modified with the "abstract" keyword; in an abstract class, there can be abstract
Object methods and member attributes, but as long as one method is abstract, the class must be declared as an abstract class, using
"abstract" to modify.
For example:
Code snippet
abstract class Demo
{
var $test;
abstract function fun1();
abstract function fun2();
function fun3()
{
....
}
}

In the above example, an abstract class "Demo" is defined and modified with "abstract", and a member is defined in this class
Attribute "$test", two abstract methods "fun1" and "fun2" and a non-abstract method fun3(); then the abstract class I
How do we use it? The most important point is that abstract classes cannot produce instance objects, so they cannot be used directly. We have
many times before As mentioned, classes cannot be used directly. We are using objects instantiated through classes, so abstract classes cannot generate instance objects.
What is the use of declaring abstract classes? We use abstract methods as templates for subclass overloading. Defining an abstract class is equivalent to
Defines a specification that requires subclasses to comply. After the subclass inherits the abstract class, the abstract method in the abstract class must be followed
Subclasses need to be implemented. The subclass must implement all abstract methods in the parent class, otherwise there are still abstract methods in the subclass, then the subclass
A class is still an abstract class, and it still cannot be instantiated; why do we have to inherit from an abstract class? Because sometimes we have to implement
Some functions must be inherited from abstract classes, otherwise you will not be able to implement these functions. If you inherit an abstract class, you must implement it
Abstract methods in;
Code snippet

abstract class Demo
{
var $test;
abstract function fun1();
abstract function fun2();
function fun3()
{
....
}
}
$demo=new Demo(); //Abstract classes can generate instance objects, so this is wrong. The instantiated objects are handed over to subclasses
class Test extends Demo
{
function fun1()
{
...
}
function fun2()
{
...
}
}
$test=new Test(); //Subclasses can instantiate objects because all abstract methods in the parent class are implemented
?> fun3 can be applied without re-implementation
12.php5 interface technology PHP, like most object-oriented programming languages, does not support multiple inheritance. That is to say, each class can only inherit one parent class. For
To solve this problem, PHP introduced interfaces. The idea of ​​interfaces is to specify a series of
that a class that implements the interface must implement. method. Interface is a special abstract class, and abstract class is a special class, so interface is also a special class, why
How about saying that an interface is a special abstract class? If all the methods in an abstract class are abstract methods, then we change it to another
The first declaration method uses "interface"; that is to say, all methods in the interface must be declared as abstract methods , and in the interface
Variables cannot be declared, and all members in the interface have public permissions. Therefore, subclasses must also use
when implementing Use public permissions.The keyword we use when declaring a class is "class", and the interface, a special class, uses the keyword
"interface";
Class definition: class class name { ... }, interface declaration: interface interface name { ... } Code snippet
//Define an interface using the interface keyword, "One" is the interface name
interface One
{
//Define a constant
const constant = 'constant value';
//An abstract method "fun1" is defined
public function fun1();
//Defined abstract method "fun2"
public function fun2();
}
?> In the above example, an interface "one" is defined, which declares two abstract methods "fun1" and "fun2", because
in the interface All the methods above are abstract methods, so when declaring abstract methods, there is no need to use "abstract" like abstract classes This keyword, this keyword has been added by default, and the "public" access permission in the interface can also be removed,
Because the default is public, because all members in the interface must be public, so we don’t
If you can use "private" and "protected" permissions, you must use public or the default. In addition, in the interface I
We also declare a constant "constant"
, because variable members cannot be used in interfaces, so we have to use const
Keyword declaration.
Because the interface is a special abstract class, all the methods in it are abstract methods, so the interface cannot generate instance objects;
It also serves as a specification that all abstract methods need to be implemented by subclasses.
We can use the "extends" keyword to let one interface inherit another interface;
Code snippet
//Use "extends" to inherit another interface
interface Two extends One
{
function fun3();
function fun4();
}
?> When we define a subclass of an interface to implement all abstract methods in the interface, the keyword used is "implements" instead of
It’s the “extends” we mentioned earlier;
Code snippet
//Use the "implements" keyword to implement the abstract methods in the interface
class Three implements One
{
function fun1()
{
....
}
function fun2()
{
....
}
}
//With all methods implemented, we can use subclasses to instantiate objects.
$three=new Three();
?>
We can also use abstract classes to implement some abstract methods in the interface, but in order to instantiate objects, this abstract class requires
Only if a subclass implements all its abstract methods;
As we said before, PHP is single inheritance. A class can only have one parent class, but a class can implement multiple interfaces, just
It is equivalent to a class having to abide by multiple norms, just like we not only have to abide by the laws of the country, but if we are in school, we also have to abide by the laws
The school rules are the same;
Code snippet
//Use implements to implement multiple interfaces
class Four implemtns Interface One, Interface Two, ... .
{
//All methods in the interface must be implemented before the object can be instantiated.
}
?>
In PHP, not only can a class implement multiple interfaces, but you can also implement multiple interfaces while inheriting a class. You must first
Inherit the class and then implement the interface;
//Use extends to inherit a class and implements to implement multiple interfaces
class Four extends class name one implemtns interface one, interface two, ... .
{
//All methods in the interface must be implemented before the object can be instantiated
... ... ... ... ..
}
?> Abstract classes allow the existence of abstract methods, but also allow the existence of non-abstract methods. Interfaces only allow abstract methods and constants to exist. Therefore, abstract methods can be inherited and implemented through interfaces, and non-abstract methods in abstract methods are called through the self:: method name. example: //The abstract class inherits the interface class and implements the methods of the interface class
abstract class Demo implements one{
var $test;
abstract function fun1();
abstract function fun2();
function fun3(){
echo "This is fun3
in the demo class";
//To call each other between methods in abstract classes, use self
self::fun4();
}
//Implement the methods in the interface in the abstract class, or in a specific subclass that inherits the abstract class
function fun4(){
echo "This is fun4
in demo class";
}
}
//Interface
interface one{
public function fun4();
}
//Inherit abstract class
class Test extends Demo{
//Override methods in abstract classes
function fun1(){
echo "This is fun1
in the Test class";
}
function fun2(){
echo "This is fun2 in the Test class";
}
//If fun3 is not rewritten, fun3 in the parent class will be automatically called when calling.
function fun3(){
echo "hello word
";
//Call the method in the parent class
parent::fun3();
}
function fun4(){
echo "hi, helllo !";


}
}
$p1 = new Test();
$p1->fun1();
$p1->fun2();
$p1->fun3();


?> Running results: This is fun1
in the Test class This is fun2
in the Test class hello word
This is fun3
in demo class This is fun4
in demo class Hi, hello!
13. Polymorphic applications Polymorphism is one of the three major object-oriented features besides encapsulation and inheritance. In my personal opinion, it can be achieved in PHP
Polymorphism, but compared with object-oriented languages ​​​​such as C++ and Java, polymorphism is not so prominent because PHP itself is a
A weakly typed language, there is no problem of converting parent class objects into subclass objects or subclass objects into parent class objects, so there are many
The application of polymorphism is not so obvious; the so-called polymorphism refers to the ability of a program to handle multiple types of objects, such as in public
When working in a company, the financial department pays wages every month. The same method of payment is applied to different employees or employees in different positions within the company
They are all paid through this method, but the wages paid are different. So there are multiple ways to pay wages
form. For object-oriented programs, polymorphism is to assign the subclass object to the parent class reference, and then call the parent class method to
Execute the method that the subclass overrides the parent class (base class: class A{})
, but it is weakly typed in PHP, and the object references are the same regardless of the parent class reference, or
Subclass reference.
Let's look at an example now. First of all, to use polymorphism, there must be a relationship between parent class objects and subclass objects. Make a shape
The interface or abstract class is used as the parent class. There are two abstract methods in it, one is to find the perimeter, and the other is to find the area;
The subclasses of this interface have many different shapes, each shape has a perimeter and area, and because the parent class is an interface, the subclasses
It is necessary to implement the two abstract methods of perimeter and area of ​​the parent class. The purpose of this is to make each subclass of different shapes comply with
According to the specifications of the parent class interface, there must be methods for calculating perimeter and area.Code snippet

//Defines a shape interface, which contains two abstract methods for subclasses to implement
interfaceShape
{
function area();
function perimeter();
}
//Define a rectangle subclass to implement the perimeter and area in the shape interface
class Rect implements Shape
{
private $width;
private $height;
function __construct($width, $height)
{
$this->width=$width;
$this->height=$height;
}
function area()
{
return "The area of ​​the rectangle is:".($this->width*$this->height);
}
function perimeter()
{
return "The perimeter of the rectangle is:".(2*($this->width+$this->height));
}
}
//Define a circle subclass to implement the perimeter and area in the shape interface
class Circular implements Shape
{
private $radius;
function __construct($radius)
{
$this->radius=$radius;
}
function area()
{
return "The area of ​​a circle is:".(3.14*$this->radius*$this->radius);
}
function perimeter()
{
return "The circumference of a circle is:".(2*3.14*$this->radius);
}
}
//Assign the subclass rectangle object to a reference of the shape
$shape=new Rect(5, 10);
echo $shape->area()."
";
echo $shape->perimeter()."
";
//Assign the subclass circle object to a reference of the shape
$shape=new Circular(10);
echo $shape->area()."
";
echo $shape->perimeter()."
";
?>
The execution result of the above example:
Execution results
The area of ​​the rectangle is: 50
The perimeter of the rectangle is: 30
The area of ​​a circle is: 314
The circumference of a circle is: 62.8
From the above example, we can see that the rectangular object and the circular object are assigned to the variable $shape respectively, and the area in the $shape reference is called
Different results appeared with the perimeter method. This is a polymorphic application. In fact, in our weak type-oriented PHP
In the language of elephants, the feature of polymorphism is not particularly obvious. It is actually the variable application of object type variables.

14. Serialize objects
Sometimes it is necessary to transmit an object over the network. In order to facilitate transmission, the entire object can be converted into a binary string and wait until
When it reaches the other end, it is restored to the original object. This process is called serialization, just like we now want to pass a car through the wheel
Shipping to the United States, because the car is relatively large, we can dismantle the car into small parts, and then we pass these parts
They are shipped to the United States by ship, and then the parts are assembled back into the car.
There are two situations where we must serialize objects. The first situation is that when transmitting an object over the network, the object
Serialization, the second case is to use serialization when writing objects to files or databases.
There are two processes in serialization. One is serialization, which is to convert the object into a binary string. We use serialize()
function to serialize an object, and the other is deserialization, which is to convert the binary string converted from the object into an object, I
We use the unserialize() function to deserialize an object.
The parameter of the serialize() function in PHP is the object name, and the return value is a string. The string returned by Serialize() contains
The meaning is ambiguous. Generally, we will not parse this string to get the object information. We only need to pass the returned string to another network
Either end or save it to the square.
The unserialize() function in PHP is used to deserialize objects. The parameter of this function is the return value of the serialize() function,
The output is of course the reorganized object.
class Person
{
//The following are the member attributes of people
var $name; //The person’s name
var $sex; //Person’s gender
var $age; //The person’s age
//Define a constructor parameter to assign values ​​to the attributes $name, gender $sex and age $age
function __construct($name="", $sex="", $age="")
{
code snippet
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//The way this person can speak is to express his own attributes
function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}
}
$p1=new Person("Zhang San", "Male", 20);
$p1_string=serialize($p1); //Serialize an object and return a string
echo $p1_string."
"; //We usually do not parse serialized strings
$p2=unserialize($p1_string); //Deserialize a serialized string into object $p2
$p2->say();
?> Execution results
O:6:"Person":3:{s:4:"name";s:4:"张三";s:3:"sex";s:2:"male";s:3:"age ";i:20;}
My name is: Zhang San Gender: Male My age is: 20
There are two magic methods in php5, __sleep() method and __wakeup() method. When the object is serialized, a
will be called. A __sleep() method is used to complete some things before going to bed; and when waking up again, that is, re-forming an object from a binary string,
Then another function of PHP, __wakeup(), will be automatically called to do some actions that the object will do when it wakes up.
The __sleep() function does not accept any parameters, but returns an array containing the properties that need to be serialized. Not included
Attributes will be ignored when serializing. Without the __sleep() method, PHP will save all attributes.Code snippet

class Person
{
//The following are the member attributes of the person
var $name; //Person’s name
var $sex; //person’s gender
var $age; //Age of person
//Define a constructor parameter to assign values ​​to the attributes name $name, gender $sex and age $age
function __construct($name="", $sex="", $age="")
{
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//The way this person can speak, tell his own attributes
function say()
{
echo "My name is:".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}
//When specifying serialization, serialize the $name and $age values ​​​​in the returned array, ignoring the attribute $sex that is not in the array.
function __sleep()
{
$arr=array("name", "age");
return($arr);
}

//When regenerating the object, reassign $age to 40
function __wakeup() {
$this->age = 40;
}
}
$p1=new Person("Zhang San", "Male", 20);
//Serialize an object, return a string, call the __sleep() method, ignore the attribute $sex that is not in the array
$p1_string=serialize($p1);
echo $p1_string."
"; //We usually do not parse serialized strings
$p2=unserialize($p1_string); //Deserialize the formed object $p2 and reassign $age to 40
$p2->say();
?>
The output value of the above example is:
Execution results
O:6:"Person":2:{s:4:"name";s:4:"Zhang San";s:3:"age";i:20;} My name is: Zhang San Gender: My age is: 40


15. Automatically load classes
When many developers write object-oriented applications, they create a PHP source file for each class definition. A big nuisance
The annoying thing is having to write a long list of include files at the beginning of each script (one file per class).
In a software development system, it is impossible to write all classes in a PHP file. When it is necessary to adjust
When using a class declared in another file, you need to introduce this file through include.But sometimes, when there are many files
In the project, it is a headache to include all the required class files one by one, so can we use
What class should we import the PHP file in which this class is located? This is the automatic loading class we are going to talk about here.
In PHP 5, you can define an __autoload() function, which will be automatically called when trying to use a class that has not been defined yet,
By calling this function, the script engine has a last chance to load the required classes before PHP fails with an error, __autoload() function
One of the parameters received by the number is the class name of the class you want to load, so when you are working on a project, you need to
when organizing the file name of the defined class. According to certain rules, it is best to center on the class name, or you can add a unified prefix or suffix to form the file name, such as
xxx_classname.php, classname_xxx.php and just classname.php and so on.
This example attempts to load the MyClass1 and MyClass2 classes from the MyClass1.php and MyClass2.php files respectively
Code snippet
function __autoload($classname)
{
require_once $classname .'.php';
}
//The MyClass1 class does not automatically call the __autoload() function, passing in the parameter "MyClass1"
$obj = new MyClass1();
//The MyClass2 class does not automatically call the __autoload() function, passing in the parameter "MyClass2"
$obj2 = new MyClass2();
?>





















www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735873.htmlTechArticleI recently re-learned the object-oriented part of PHP, took notes and shared them with everyone, part of which is For your own profile, the colored parts are generally what you think are the key points or needs...
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