Home  >  Article  >  Backend Development  >  PHP object-oriented overloading

PHP object-oriented overloading

不言
不言Original
2018-06-06 10:05:461197browse

This article mainly introduces the object-oriented overloading of PHP, which has certain reference value. Now I share it with you. Friends in need can refer to it.

Definition:

1 ) dynamically "creates" the properties and methods of a class.

2) Achieved through magic method.

3) When calling a property or method of a class that is undefined or invisible in the current environment, the overloaded method will be called.

Attribute overloading

__set      赋值

__get      读取

__isset    判断是否存在

__unset    销毁

Example

// 属性的重载
class Person
{
    public $name = '小芳';
    protected $age = 18;

    public function __get($n)
    {
        //echo '试图读取不可访问的属性'.$n;

        if( $n == 'age'){
            return $this -> age;
        }else{
            return '你要查户口吗?';
        }
    }

    public function __set($n,$v)
    {
        //echo &#39;试图设置不可访问的属性&#39;,&#39;<br/>&#39;;
        $this -> $n = $v;
    }

    public function __isset($n)
    {
        echo &#39;判断不可访问的属性&#39;.$n.&#39;是否存在&#39;,&#39;<br/>&#39;;
    }

    public function __unset($n)
    {
        echo &#39;销毁不可访问的属性&#39;.$n,&#39;<br/>&#39;;
    }
}

$p1 = new Person();

// 读取
//echo $p1 -> age,&#39;<br/>&#39;;
//echo $p1 -> xxx,&#39;<br/>&#39;;

// 设置
//$p1 -> age = 30;
//echo $p1 -> age,&#39;<br/>&#39;;

// 判断存在与否
isset($p1 -> age);

// 销毁
unset($p1 -> age);

Method overloading

__call         调用不可访问的普通方法

__callStatic   调用不可访问的静态方法

Special note that when __callStatic is defined, it must be defined as a static method.

Example

<?php

class MyClass
{
    protected function func($n)
    {
        echo &#39;这是一个不可访问的方法&#39;;
        echo &#39;参数有&#39;.$n;
    }

    protected static function fun2()
    {
        echo &#39;受保护的静态方法&#39;;
    }

    public function __call($function_name,$args)
    {
        echo &#39;触发了不可访问的方法&#39;;
        var_dump($function_name);
        var_dump($args);
    }

    public static function __callStatic($function_name,$args)
    {
        echo &#39;触发了不可访问jing tai方法,静态!!!!&#39;;
        var_dump($function_name);
        var_dump($args);
    }
} 

// 实例化
$c1 = new MyClass();

$c1 -> func([1,2,3]);

$c1 -> func2([1,2,3]);

Related recommendations:

php object-oriented encapsulation

##php Object-oriented magic methods

php object-oriented static methods, properties and constants

The above is the detailed content of PHP object-oriented 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