Home Backend Development PHP Tutorial PHP object-oriented, automatic loading of classes, object serialization, polymorphic application_PHP tutorial

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

Jul 20, 2016 am 11:10 AM
php load exist Polymorphism object application article of kind automatic For

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles