PHP 常见魔术方法简单例子

<?php

class Test
{
    private $priAttr;
    private $data = [];
    public $objA;
    public $objB;

    public $pubAttr;

    public function __construct($priAttr, $pubAttr)
    {
        $this->priAttr = $priAttr;
        $this->pubAttr = $pubAttr;
        $this->objA = new TestA;
        $this->objB = new TestB;
    }

    public function __get($name)
    {
        print_r('getting unexist attr => ' . $name . PHP_EOL);
        return $this->data[$name] ?: '';
    }

    public function __set($name, $value)
    {
        print_r('setting unexist attr => ' . $name . ', value => '. $value . PHP_EOL);
        return $this->data[$name] = $value;
    }

    public function __isset($name)
    {
        print_r('isset unexist attr => ' . $name . PHP_EOL);
        return $this->data[$name] ? true : false;
    }

    public function __unset($name)
    {
        print_r('unset unexist attr => ' . $name . PHP_EOL);
        unset($this->data[$name]);
        return true;
    }

    public function __call($name, $arguments)
    {
        print_r('call unexist method => ' . $name . PHP_EOL);
        return call_user_func_array([$this, 'xxx'], $arguments);
    }

    private function xxx($a, $b = '', $c = '')
    {
        echo 'hello! im xxx method! a:'. $a . ',b:' . $b . ',c:' . $c . PHP_EOL;
    }

    public static function __callStatic($name, $arguments)
    {
        print_r('call unexist static method => ' . $name . PHP_EOL);
        return call_user_func_array([__CLASS__, 'xxxStatic'], $arguments);
    }

    private static function xxxStatic($a, $b = '', $c = '')
    {
        echo 'hello! im xxx static method! a:'. $a . ',b:' . $b . ',c:' . $c . PHP_EOL;
    }

    public function getPriAttr()
    {
        return $this->priAttr;
    }

    public function __invoke()
    {
        print_r('try to use class '. __CLASS__ .' as method' . PHP_EOL);
    }

    public function __clone()
    {
        print_r('clone objA' . PHP_EOL);
        $this->objA = clone $this->objA;
    }
}

class TestA
{
    public $flag = 'testA';
}

class TestB
{
    public $flag = 'testB';
}

$test = new Test('priAttr', 'pubAttr');
print_r($test->getPriAttr() . PHP_EOL);// private attr
print_r($test->pubAttr . PHP_EOL);//public attr

$test->a = 'a';//__set
print_r($test->a . PHP_EOL);//__get

$test->hello(1,2,3);//__calll

Test::hi(4,5,6);//__callStatic

$test();//__invoke

$cloneTest1 = clone $test;//clone
$test->pubAttr = 'pubAttr1';
echo $cloneTest1->pubAttr . PHP_EOL;
$test->objA->flag = 'testAA';
echo $cloneTest1->objA->flag . PHP_EOL;
$test->objB->flag = 'testBB';
echo $cloneTest1->objB->flag . PHP_EOL;
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!