Table of Contents
Overloading" >Overloading
Attribute overloading" >Attribute overloading
Value: " >Value:
Assignment: " >Assignment:
Judgment (isset):" >Judgment (isset):
Destruction (unset):" >Destruction (unset):
Magic method" >Magic method
GET($property name):" >GET($property name):
SET ($attribute name, value): " >SET ($attribute name, value):
ISSET ($attribute name): " >ISSET ($attribute name):
UNSET($property name)" >UNSET($property name)
方法重载" >方法重载
Home Backend Development PHP Tutorial PHP object-oriented - sample code detailing overloading

PHP object-oriented - sample code detailing overloading

Mar 25, 2017 am 10:07 AM

Overloading

"Overloading" in PHP is different from most other object-oriented languages, except that they all use the same noun. . Traditional "overloading" is used to provide multiple class methods with the same name, but each method has different parameter types and numbers. The "overloading" provided by PHP refers to dynamically "creating" class properties and methods. The overloaded method will be called when a class attribute or method that is undefined or invisible is called. It is achieved through magic methods.
Generally speaking, defining all member attributes in a class as private is more in line with realistic logic and can better protect members in the class. However, reading and assigning operations to member properties are very frequent, and it is very, very troublesome to define for each private property in the class a public method that can be obtained and assigned outside the object. Therefore, in versions after PHP 5.1.0, two methods "get()" and "set()" are predefined, which are used to obtain and assign values ​​to all private attributes used, and to check whether the private attributes exist. The method "isset()" and the method "unset()" used to delete private properties in the object.
In layman’s terms, the meaning of overloading in PHP refers to some of the “processing mechanisms” when an object or class uses its undefined or invisible properties and methods.

Attribute overloading

When using an attribute that does not exist in an object, the preset response method (processing method) in this class mechanism).
Attributes are essentially variables, which have only 4 operations:

Value:

When correct When a property of an object that does not exist (undefined or invisible) is "retrieved", the method is automatically called: the GET() method is not case-sensitive.

Assignment:

When "assigning" a property that does not exist (undefined or invisible) to an object, it will automatically Calling method: SET()

Judgment (isset):

When a property of an object does not exist (undefined or invisible) When making isset() judgment, the method will be called automatically: isset()

Destruction (unset):

When an object is no longer When an existing (undefined or invisible) attribute is judged by unset(), the method will be automatically called: unset()

The above four methods are called magic methods.

Magic method

GET($property name):

A method that will be automatically called when "getting a value" for a non-existent attribute of an object. This method can take a formal parameter, indicating the name of the non-existent attribute to be fetched ( characters String ), you can use this method to perform some special processing on unexpected situations.

For example:

<?phpclass A{
    public  $p1 = 1;
}$a1 = new A();echo $a1->p1;  //1echo $a1->p2;	//未定义$p2,会报错, Notice: Undefined property: A::$p2?>
Copy after login

Overloading of php, use the get() method to "gracefully handle" the above error.

<?php<?phpclass A{
    public  $p1 = 1;    
    //private $p2 = 1;  
    //这里将属性私有化,其实和未定义一样,对外部来说都相当于不存在

    function get($prop_name){

        /*
        //比如可以这样处理
        echo "<br />{$prop_name}属性还未定义(不存在)!";
        return "";  //也可以返回0,或false等
        */

        //还可以这样处理
        trigger_error("发生错误:属性不存在!", E_USER_ERROR);        
        die();
    }
}$a1 = new A();echo $a1->p1;  //1echo $a1->p2;	//未定义$p2,但经过"处理"?>
Copy after login

Here is an example of an operation to obtain the private properties used.

Example:

<?phpclass Person{
    public $name;  
    public $sex;    
    private $age;  //年龄私有化,类外不能直接访问这个属性    

    function construct($name=&#39;&#39;, $sex=&#39;&#39;, $age){
        $this->name = $name;        
        $this->sex = $sex;        
        $this->age = $age;   
    }    private function get($propertyName){ //这里要用private修饰,防止类外部调用
        if($propertyName == &#39;age&#39;){            
        return $this->age;
        }
    }
}$p = new Person(&#39;yeoman&#39;, &#39;男&#39;,23);
$v1 = $p->name;$v2 = $p->sex;$v3 = $p->age;    
//自动调用了get()方法获取私有属性age(函数定义里面返回)
echo "name=$v1, sex=$v2, age=$v3";?>
Copy after login

The running result is:

name=yeoman, sex=男, age=23
Copy after login

SET ($attribute name, value):

When "assigning" a non-existent attribute of an object, this internal magic method will be automatically called; it has two formal parameters, representing the "attribute name" and "attribute name" to which the non-existent attribute is to be assigned, respectively. "Attribute value".
This method, combined with the _GET method, can often make the class we define more extensible. That is: the attributes of a class or object can be more convenient and free.

Example:

<?phpclass A{
    //定义一个属性,
    protected $prop_list = array();    
    //初始为空数组

    //这个方法会在A的对象使用一个不存在的属性进行赋值时调用
    function set($p,$v){
        //echo "使用不存在的属性!";
        $this->prop_list[$p] = $v;     
    }    function get($p){
        return $this->prop_list[$p];    
    }
}$a1 = new A();$a1->p1 = 1;   
//不存在的属性名赋值,此时会调用_set(),并传过去"p1"和1$a1->p2 = 2;$a1->ac = &#39;avc&#39;;
echo "<br />输出这些“不存在的属性”的值:";
echo "<br />a1->p1:" . $a1->p1;    
//不存在的属性名取值,此时会调用_get(),并传过去"p1"echo "<br />a1->p2:" . $a1->p2;echo "<br />a1->ac:" . $a1->ac;?>
Copy after login

The running result is:

输出这些“不存在的属性”的值:a1->p1:1a1->p2:2a1->ac:avc
Copy after login

ISSET ($attribute name):

When isset() is judged for a property that does not exist in an object, the internal method will be automatically called: isset();

Usage:

$v1 = isset($对象->不存在的属性);    //此时会调用这个对象所属类中的魔术方法:isset()
Copy after login

Example:

<?phpclass A{
    //定义一个属性,
    protected $prop_list = array();    //初始为空数组

    //这个方法会在A的对象使用一个不存在的属性进行赋值时调用
    function set($p,$v){
        //echo "使用不存在的属性!";
        $this->prop_list[$p] = $v;     
    }    function get($p){
        if($this->prop_list[$p]){            return $this->prop_list[$p];
        }else{            return "该属性不存在!";
        }
    }    function isset($prop){   //isset()是自定义的方法, isset()是系统函数
        $re = isset($this->prop_list[$prop]);        return $re;
    }
}
$a1 = new A();
$a1->p1 = 1;//不存在的属性名赋值,此时会调用_set(),并传过去"p1"和1
$a1->p2 = 2;
$a1->ac = &#39;avc&#39;;
echo "<br />输出这些“不存在的属性”的值";
echo "<br />a1->p1:" . $a1->p1;//不存在的属性名取值,此时会调用_get(),并传过去"p1"
echo "<br />a1->p2:" . $a1->p2;
echo "<br />a1->ac:" . $a1->ac;
//下面演示isset判断不存在的属性
$v1 = isset($a1->p1);  //存在
$v2 = isset($a1->ppp1);    //不存在
var_dump($v1);echo "<br />";
var_dump($v2);?>
Copy after login

Running results:

输出这些“不存在的属性”的值
a1->p1:1a1->p2:2a1->ac:avc

boolean trueboolean false
Copy after login

UNSET($property name)

When unset() is used to destroy a property that does not exist in an object, The internal method will be automatically called: unset();

<?phpclass A{
    //定义一个属性,
    protected $prop_list = array();    
    //初始为空数组

    //这个方法会在A的对象使用一个不存在的属性进行赋值时调用
    function set($p,$v){
        //echo "使用不存在的属性!";
        $this->prop_list[$p] = $v;     
    }    function get($p){
        if($this->prop_list[$p]){            
        return $this->prop_list[$p];
        }else{            
        return "该属性不存在!";
        }
    }    function unset($prop){
        unset($this->prop_list[$prop]); 
    }
}$a1 = new A();
$a1->p1 = 1;//不存在的属性名赋值,此时会调用_set(),并传过去"p1"和1
echo "<br />a1->p1:" . $a1->p1;//不存在的属性名取值,此时会调用_get(),并传过去"p1"//下面演示unset销毁一个不存在的属性
unset($a1->p1);
echo "<br />a1->p1:" . $a1->p1;?>
Copy after login

The running result is:

a1->p1:1a1->p1:该属性不存在!
Copy after login

In the following example, declare a Person class and set all member attributes to private. Add two custom "isset()" and "unset()" methods to the class. These two methods will be automatically called when using "isset()" and "unset()"functions outside the class. The code is as follows:

<?php
class Person{
    private $name; //此属性被封住
    private $sex;
    private $age;

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

    private function __isset($propertyName){   //需要一个参数,是测定的私有属性的名称
        if($propertyName == &#39;name&#39;){
            return false;   //返回假,不允许在类外部测定name属性   
        }
        return isset($this->$propertyName);   //这里propertyName要加$符,因为这是参数,不是属性
    }                       

    private function __unset($propertyName){
        if($propertyName == &#39;name&#39;)
            return; //退出方法,不允许删除对象中的name属性
        unset($this->$propertyName);  //这里propertyName要加$符
    }

    public function say(){
        echo "名字:" . $this->name . ",性别:" . $this->sex . ",年龄:" . $this->age . "<br />"; 
    }

}

$person = new Person("yeoman", "男", 23);

var_dump(isset($person->name));    //输出bool(false),不允许测定name属性
var_dump(isset($person->sex)); //输出bool(true),存在sex私有属性
var_dump(isset($person->age)); //输出bool(true),存在age私有属性
var_dump(isset($person->id));  //输出bool(false),测定对象中不存在id属性

unset($person->name);  //删除私有属性name,但在 __unset()中不允许删除
unset($person->sex);   //删除对象中的私有属性sex,删除成功
unset($person->age);

$person->say();    //对象中的sex和age属性被删除,输出:名字:yeoman,性别:,年龄:
?>
Copy after login

Running results:

boolean falseboolean trueboolean trueboolean false名字:yeoman,性别:,年龄:
Copy after login

方法重载

  当对一个对象不存在的实例方法进行“调用”时,会自动调用类中的call()这个魔术方法;
  当对一个类不存在的静态方法进行“调用”时,会自动调用类中的callstatic()这个魔术方法。

例子:直接调用不存在的方法

<?phpini_set(&#39;display_errors&#39;,1);class A{}$a = new A();$a->f1();  //不存在的方法?>
Copy after login

  会报错,报错内容为:

Fatal error: Uncaught Error: Call to undefined method A::f1()
Copy after login

  对上面报错作“优雅处理”:

<?phpclass A{
    //当对这个类的对象不存在的实力方法进行调用时,会自动调用本方法
    //这个方法必须带2个形参:
    //$methodName:表示要调用的不存在的方法名;
    //$argument:表示要调用该不存在的方法时,所使用的实参数据,是一个数组。
    function call($methodName, $argument){
        //echo "call被调用了!";
        echo $methodName . "()方法不存在!";
    }
}$a = new A();$a->f1();  //不存在的方法,但经过处理?>
Copy after login

  运行结果为:

f1()方法不存在!
Copy after login

  当对一个类不存在的静态方法进行“调用”时,会自动调用类中的callstatic()这个魔术方法。和上面的处理类似。

The above is the detailed content of PHP object-oriented - sample code detailing overloading. For more information, please follow other related articles on the PHP Chinese website!

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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.

See all articles