How to implement this feature in PHP?
Question
When accessing member that doesn't exist, automatically creates the object.
$obj = new ClassName();
$newObject = $ojb->nothisobject;
Is it possible?
Solution
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.
OTHER TIPS
Use the magic overloading functions
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;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow