search
HomeBackend DevelopmentPHP TutorialPHP object-oriented, automatic loading of classes, object serialization, polymorphic application_PHP tutorial

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
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment