类属性、方法重载

原创 2018-11-23 15:47:34 267
摘要:class Father {     public static $money = 800;     public static function getClass(){      &nb
class Father
{
    public static $money = 800;

    public static function getClass(){
        return __CLASS__;
    }
    public static function getMoney(){
//        return self::getClass().':::::'.self::$money;
        //static用在静态继承的上下文中,动态设置静态成员的调用者
        return static::getClass().':::::'.static::$money;
    }
}

class Child extends Father {
    //复写父类的属性
    public static $money = 600;
    //复写父类的方法
    public static function getClass(){
        return __CLASS__;
    }
}

echo Father::getClass(),'<br>';
echo Father::getMoney(),'<br>';
echo Child::$money,'<br>';
echo Child::getClass(),'<hr>';
echo Child::getMoney(),'<br>';

//重载:动态创建类的属性和方法,通过魔术方法实现。魔术方法的调用者是php本身而非用户
const IS_ISSET = true;
const IS_GET = true;
const IS_SET = true;
const IS_UNSET = false;
class Visit
{
    protected $data = [];
    public function __isset($name)
    {
        return IS_ISSET && isset($this->data[$name]);
    }

    public function __get($name)
    {
        return IS_GET ? $this->data[$name] : '非法';
    }

    public function __set($name, $value)
    {
        return IS_SET ? $this->data[$name] = $value : '禁止访问';
    }

    public function __unset($name)
    {
        if(IS_UNSET){
            unset($this->data[$name]);
        }else echo '不能效销毁';
    }
}

$visit = new Visit();
if(isset($visit->table)){
    echo $visit->table,'<br>';
}else $visit->table = 'table_table';
echo $visit->table,'<br>';

$visit->table = 'table_text';
echo $visit->table,'<br>';

unset($visit->table);
echo $visit->table,'<hr>';

class Site
{
    public function show($arg){
        $title = func_get_arg(0);
        $desc = func_get_arg(1);
        return 'Site::show():<br>名称:'.$title.'<br>描述:'.$desc;
    }
    public static function add($arg){
        $m = func_get_arg(0);
        $n = func_get_arg(1);
        return 'Site::add():<br>' . $m . '+' . $n . '=' . ($m + $n);
    }
}

//方法重载
class Web
{
    public function __call($name, $arguments)
    {
//        return '方法:'.$name.'<br>参数列表:'.var_export($arguments,true);
        //方法重载:用在跨类的方法调用
        return call_user_func_array([(new Site),'show'],$arguments);
    }
    public static function __callStatic($name, $arguments)
    {
        return call_user_func_array([(new Site),'add'],$arguments);
    }
}

$web = new Web();
//输出:
//Site::show():
//名称:php_curse
//描述:hello world
echo $web->show('php_curse','hello world'),'<br>';
//输出:
//Site::add():
//20+30=50
echo Web::add(20,30);


批改老师:韦小宝批改时间:2018-11-23 15:50:21
老师总结:嗯!写的很不错!很完整!但是缺少自己的总结哦!下次记得加上自己的总结!继续加油吧!

发布手记

热门词条