1

このステートメントの 2 番目のプロパティまたはメソッドにアクセスする方法

$this->test->hello();

私の中では、プロパティが__get()何であるかを理解する方法しか理解できません。test「hello」メソッド呼び出しもキャプチャできるようにしたいです。そしてそれを使っていくつかの動的なことをします。

要するに、私が入力すると

$this->test->hello()

echoセグメントごとにしたい

echo $propert // test
echo $method //hello

問題は、私のテストが外部クラスから新しいクラス オブジェクトをインスタンス化するために使用されていることです。メソッドはクラス オブジェクトhelloに属します。test

私は私の中にメソッドをキャプチャしたい__get().

これどうやってするの?

編集:

public function __get($name)
        {
            if ($name == 'system' || $name == 'sys') {

                $_class = 'System_Helper';

            } else {

                foreach (get_object_vars($this) as $_property => $_value) {

                    if ($name == $_property)
                        $_class = $name;
                }
            }

            $classname = '\\System\\' . ucfirst($_class);
            $this->$_class = new $classname();

            //$rClass = new \ReflectionClass($this->$_class);
            $rClass = get_class_methods($this->$_class);
            foreach($rClass as $k => $v)
            echo $v."\n";
            //print_r($rClass);

            return $this->$_class;
4

3 に答える 3

1

あなたはある種のプロキシクラスを求めているようです。これはあなたのニーズに合っているかもしれません。

class ObjectProxy {
    public $object;

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

    public function __get($name) {
        if (!property_exists($this->object, $name)) {
            return "Error: property ($name) does not exist";
        }
        return $this->object->$name;
    }

    public function __call($name, $args) {
        if (!method_exists($this->object, $name)) {
            return "Error: method ($name) does not exist";
        }
        return call_user_func_array(array($this->object, $name), $args);
    }
}

class A {
    public $prop = 'Some prop';

    public function hello() {
        return 'Hello, world!';
    }
}

class B {
    public function __get($name) {
        if (!isset($this->$name)) {
            $class_name = ucfirst($name);
            $this->$name = new ObjectProxy(new $class_name);
        }
        return $this->$name;
    }
}
$b = new B();
var_dump($b->a->hello());
var_dump($b->a->prop);
var_dump($b->a->foo);
var_dump($b->a->bar());

出力:

string 'Hello, world!' (length=13)
string 'Some prop' (length=9)
string 'Error: property (foo) does not exist' (length=36)
string 'Error: method (bar) does not exist' (length=34)

例:

http://ideone.com/dMna6

__set__callStatic__isset__invokeなどの他の魔法のメソッドに簡単に拡張できます。

于 2012-05-02T00:35:58.963 に答える
0

インスタンス化したオブジェクト$thisは、__getマジック メソッドを使用してオブジェクトを (プロパティとして) 作成しますtest。に格納されているオブジェクトは、定義されていない場合に使用するマジック メソッドを$this->test実装する必要があります。__callhello()

于 2012-05-02T00:30:50.230 に答える
0

__callの代わりに使いたいと思います__get。また、しないでください。

于 2012-05-02T00:22:10.243 に答える