PHP object-oriented, automatic loading of classes, object serialization, polymorphic application_PHP tutorial

WBOY
Release: 2016-07-20 11:10:55
Original
833 people have browsed it

This article introduces application examples of automatic loading classes, object serialization, and polymorphic applications in object-oriented PHP. Students who need to know more can take a look.

Auto-loading classes
When many developers write object-oriented applications, they create a PHP source file for each class definition. A big annoyance 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 a PHP file needs to call a class declared in another file, it needs to be included through include. File import. However, sometimes, in projects with many files, it is a headache to include all the files of the required classes one by one. So, can we include this class when it is used? Where to import the php file? This is the autoloading 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 yet been defined. By calling this function, the script engine has the last one before PHP fails with an error. Opportunity to load the required class. One parameter received by the __autoload() function is the class name of the class you want to load. So when you are working on a project, you need to follow certain rules when organizing the file names of the defined classes. It is best to use The class name is the center. You can also add a unified prefix or suffix to form the file name, such as xxx_classname.php, classname_xxx.php and just classname.php, etc.

In this example, try to start from MyClass1.php and MyClass2 respectively. Load the MyClass1 and MyClass2 classes in the .php file

The code is as follows Copy code
 代码如下 复制代码

function __autoload($classname)
{
    require_once $classname . '.php';
}

//MyClass1类不存在自动调用__autoload()函数,传入参数”MyClass1”
$obj  = new MyClass1();

//MyClass2类不存在自动调用__autoload()函数,传入参数”MyClass2”
$obj2 = new MyClass2();

function __autoload($classname){ require_once $classname . '.php';}//MyClass1 class does not exist and automatically calls the __autoload() function. Pass in the parameter "MyClass1"$obj = new MyClass1();//MyClass2 class does not exist and automatically calls __autoload() Function, pass in the parameter "MyClass2"$obj2 = new MyClass2();


Object serialization
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 when it reaches the other end, Restore to the original object, this process is called serialization, just like we want to transport a car to the United States by ship now, because the car is relatively large, we can disassemble the car into small parts, and then We ship these parts to the United States by wheel, and then assemble these parts back into the car.

There are two cases where we must serialize the object. The first case is to serialize the object when transmitting it on the network. The second case is to write the object to a file or Serialization is used when it is a database.

There are two processes in serialization. One is serialization, which is to convert the object into a binary string. We use the serialize() function to serialize an object, and the other is deserialization. , which is to convert the object-converted binary string into an object. 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() has ambiguous meaning. Generally, we will not parse this string to get the object information. We only need to pass the returned string to the other end of the network or save it in the component.

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.

The code is as follows Copy code td>
 代码如下 复制代码

class Person
{
    //下面是人的成员属性
    var $name;  //人的名子
    var $sex;    //人的性别
    var $age;    //人的年龄

    //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值
    function __construct($name="", $sex="", $age="")
    {
        $this->name=$name;
        $this->sex=$sex;
        $this->age=$age;
    }

    //这个人可以说话的方法, 说出自己的属性
    function say()
    {
        echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."";
    }
}

$p1=new Person("张三", "男", 20);

$p1_string=serialize($p1); //把一个对象串行化,返一个字符串

echo $p1_string."";  //串行化的字符串我们通常不去解析

$p2=unserialize($p1_string);  //把一个串行化的字符串反串行化形成对象$p2

$p2->say();

class Person{ //The following are the member attributes of the person var $name; //The person’s name var $sex; //The person’s gender var $age ; //Age of a 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 ; } //This person can speak by telling his 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 stringecho $p1_string.""; //We usually do not parse serialized strings$p2=unserialize($p1_string); //Deserialize a serialized string Form object $p2$p2->say();

Application of polymorphism
Polymorphism is one of the three major characteristics of object-oriented objects besides encapsulation and inheritance. In my personal opinion, although polymorphism can be achieved in PHP, But compared with object-oriented languages ​​​​such as C++ and Java, polymorphism is not so prominent, because PHP itself is a weakly typed language, and there is no conversion of parent class objects into subclass objects or subclass objects into The problem of parent class objects, so 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. For example, when working in a company, the financial department pays wages every month, and the same payer Wages are paid to different employees or employees in different positions within the company through this method, but the wages paid are all different. Therefore, the same method of paying wages appears in many forms. 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 of the subclass overriding the parent class, but in PHP it is weakly typed, and the object reference They are all the same regardless of 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 interface or abstract class 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 are a variety of different shapes, each Shapes have perimeter and area, and because the parent class is an interface, the subclass must implement the two abstract methods of perimeter and area of ​​the parent class. The purpose of this is to make the subclass of each different shape All classes comply with the specifications of the parent class interface and have methods for calculating perimeter and area.

//Defines a shape interface, which has two abstract methods for subclasses to implement interface Shape
The code is as follows
 代码如下 复制代码

//定义了一个形状的接口,里面有两个抽象方法让子类去实现
interface Shape
{
    function area();
    function perimeter();
}

//定义了一个矩形子类实现了形状接口中的周长和面积
class Rect implements Shape
{
    private $width;
    private $height;

    function __construct($width, $height)
    {
        $this->width=$width;
        $this->height=$height;
    }

    function area()
    {
        return "矩形的面积是:".($this->width*$this->height);
    }

    function perimeter()
    {
        return "矩形的周长是:".(2*($this->width+$this->height));
    }
}

//定义了一个圆形子类实现了形状接口中的周长和面积
class  Circular implements Shape
{
    private $radius;

    function __construct($radius)
    {
        $this->radius=$radius;
    }

    function area()
    {
        return "圆形的面积是:".(3.14*$this->radius*$this->radius);
    }

    function perimeter()
    {
        return "圆形的周长是:".(2*3.14*$this->radius);
    }

//把子类矩形对象赋给形状的一个引用
$shape=new Rect(5, 10);

echo $shape->area()."
";
echo $shape->perimeter()."
";

//把子类圆形对象赋给形状的一个引用
$shape=new Circular(10);

echo $shape->area()."
";
echo $shape->perimeter()."
";

上例执行结果:
矩形的面积是:50
矩形的周长是:30
圆形的面积是:314
圆形的周长是:62.8

Copy code

{ function area(); function perimeter( );}//Defines a rectangle subclass that implements the perimeter and area in the shape interfaceclass 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)); } }//Defines a circular subclass that implements the perimeter and area in the shape interfaceclass Circular implements Shape{ private $radius; function __construct($radius) { $this->radius=$radius; } function area() { return "circle" The area of ​​the shape is: ".(3.14*$this->radius*$this->radius); } function perimeter() { return "circle The perimeter 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 circular object to a reference of the shape$shape=new Circular(10);echo $shape->area(). "";echo $shape->perimeter()."";The execution result of the above example:The area of ​​the rectangle is: 50The area of ​​the rectangle Perimeter is: 30The area of ​​a circle is: 314The circumference of a circle is: 62.8 Okay, we have details about these three It’s introduced. If you don’t understand, you can search it on Baidu.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444696.htmlTechArticleThis article introduces the application of automatic loading class object serialization polymorphism in object-oriented php Application examples, students who need to know more can take a look. Automatic loading of classes Many developers...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!