开发者

How to implement this feature in PHP?

When accessing member that doesn't exist, autom开发者_Go百科atically creates the object.

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

Is it possible?


Use the magic overloading functions


You can achieve this kind of functionality with Interceptor __get()

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

Though example in the previous post will work just fine also when the attribute is changed to public so you can access it from outside.


If you mean lazy initalization, this is one of many ways:

class SomeClass
{
    private $instance;

    public function getInstance() 
    {
        if ($this->instance === null) {
            $this->instance = new AnotherClass();
        }
        return $this->instance;
    }
}


$obj = new MyClass();

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

Use the following Lazy loading pattern:

<?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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜