3

存在しないメンバーにアクセスすると、自動的にオブジェクトを作成します。

$obj = new ClassName();
$newObject = $ojb->nothisobject;

出来ますか?

4

4 に答える 4

3

魔法のオーバーロード関数を使用する

于 2010-02-21T16:15:24.217 に答える
0

遅延初期化を意味する場合、これは多くの方法の 1 つです。

class SomeClass
{
    private $instance;

    public function getInstance() 
    {
        if ($this->instance === null) {
            $this->instance = new AnotherClass();
        }
        return $this->instance;
    }
}
于 2010-02-21T16:16:44.923 に答える
0

この種の機能は、Interceptor __get() で実現できます。

class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}

前の投稿の例は、属性をパブリックに変更して外部からアクセスできるようにしても問題なく動作します。

于 2010-02-21T16:35:38.373 に答える
0
$obj = new MyClass();

$something = $obj->something; //instance of Something

次の遅延読み込みパターンを使用します。

<?php

class MyClass
{
    /**
     * 
     * @var something
     */
    protected $_something;

    /**
     * Get a field
     *
     * @param  string $name
     * @throws Exception When field does not exist
     * @return mixed
     */
    public function __get($name)
    {
        $method = '_get' . ucfirst($name);

        if (method_exists($this, $method)) {
            return $this->{$method}();
        }else{
            throw new Exception('Field with name ' . $name . ' does not exist');
        }
    }

    /**
     * Lazy loads a Something
     * 
     * @return Something
     */
    public function _getSomething()
    {
        if (null === $this->_something){
            $this->_something = new Something();
        }

        return $this->_something;
    }
}
于 2010-02-21T16:39:09.983 に答える