Come implementare questa funzionalità in PHP?
Domanda
Quando si accede a un membro che non lo fa exist, crea automaticamente il file oggetto.
$obj = new ClassName();
$newObject = $ojb->nothisobject;
È possibile?
Soluzione
È possibile ottenere questo tipo di funzionalità con Interceptor __get ()
class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}
Anche se ad esempio nel post precedente funzionano bene anche quando l'attributo viene modificato in pubblico in modo da potervi accedere dall'esterno.
Altri suggerimenti
Utilizza il magia funzioni sovraccarico
Se intendi inizializzazione pigra, questo è uno dei tanti modi:
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
Con il seguente schema lazy loading:
<?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;
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow