[资料]PHP中的__call使用

PHP中的__call使用

官方文档:http://cn2.php.net/__call

public mixed __call ( string $name , array $arguments )
public static mixed __callStatic ( string $name , array $arguments )
当调用一个不可访问方法(如未定义,或者不可见)时,__call() 会被调用。

当在静态方法中调用一个不可访问方法(如未定义,或者不可见)时,__callStatic() 会被调用。

$name 参数是要调用的方法名称。$arguments 参数是一个数组,包含着要传递给方法$name 的参数。

Demo 1

<?php
class PersonWriter {

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

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

class Person {
    private $writer;

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

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

    function getName()  { return "Bob"; }
    function getAge() { return 44; }
}

$person= new Person( new PersonWriter() );
$person->writeName();
$person->writeAge();
?>

 

 

posted @ 2012-12-04 15:54  Athrun  阅读(202)  评论(0编辑  收藏  举报