如何在PHP中实现此功能?

时间:2010-02-21 16:12:57

标签: php class accessor

  

访问没有的成员时   存在,自动创建   对象

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

有可能吗?

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

如果您的意思是延迟初始化,这是以下几种方法之一:

class SomeClass
{
    private $instance;

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

答案 2 :(得分:0)

您可以使用Interceptor __get()

实现此类功能
class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}

虽然上一篇文章中的示例也可以在属性更改为public时正常工作,因此您可以从外部访问它。

答案 3 :(得分: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;
    }
}