魔术方法(拦截器)

2019-07-18  本文已影响0人  幻无虚生
<?php
class PersonWrite{

    function writeName(Person $p){
        print $p->getName()."\n";
    }


    function writeAge(Person $p){
        print $p->getAge()."\n";
    }

}



class Person{
    private $writer;

    public function __construct(PersonWrite $writer){
            $this->writer=$writer;
    }

    public function __call($mothod,$args){
        if(method_exists($this->writer,$mothod)){
            return $this->writer->$mothod($this);
        }
    }


    function getName(){
        return "Bob";
    }

    function getAge(){
        return "44";
    }

    public function __toString()
    {

       return $this->getAge();
    }

}


$person=new Person(new PersonWrite());

$person->writeName();
上一篇下一篇

猜你喜欢

热点阅读