Home  >  Article  >  Backend Development  >  PHP object-oriented - sample code detailing overloading

PHP object-oriented - sample code detailing overloading

黄舟
黄舟Original
2017-03-25 10:07:151362browse

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

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,但经过"处理"?>

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";?>

The running result is:

name=yeoman, sex=男, age=23

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;?>

The running result is:

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

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()

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);?>

Running results:

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

boolean trueboolean false

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;?>

The running result is:

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

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,性别:,年龄:
?>

Running results:

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

方法重载

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

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

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

  会报错,报错内容为:

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

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

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

  运行结果为:

f1()方法不存在!

  当对一个类不存在的静态方法进行“调用”时,会自动调用类中的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:
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