2
A
回答
0
可以實現這種功能與攔截__get()
class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}
儘管上一篇文章中的示例在將屬性更改爲public時也可以正常工作所以你可以從外面訪問它。
3
0
如果你的意思懶initalization,這是衆多方法之一:
class SomeClass
{
private $instance;
public function getInstance()
{
if ($this->instance === null) {
$this->instance = new AnotherClass();
}
return $this->instance;
}
}
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;
}
}
相關問題
- 1. 無法在PHP循環中實現此次Ago功能
- 2. Silverlight - 如何實現此功能?不錯的功能
- 3. 如何在Flex中實現AJAX功能
- 4. 如何在clisp中實現「doc」功能?
- 5. 功能如何do_raw_spin_lock在Linux中實現
- 6. 如何在PHP中實現「誰在線」功能?
- 7. 如何在PHP中實現這樣的呼叫中心功能?
- 8. 如何在PHP中實現c的#def功能
- 9. 如何在PHP中實現這樣的功能?
- 10. 如何在PHP中實現DataList(asp.net)的一種功能?
- 11. 如何實現diff功能?
- 12. 如何實現MenuStrip功能?
- 13. 如何實現Gmail郵件這樣的功能映射此功能
- 14. 如何使用此功能實現jQuery插件?
- 15. 如何實現此功能的掃描儀?
- 16. 如何實現Corona中的「NSUserDefaults」功能?
- 17. 如何使此PHP功能更有效
- 18. 此語言功能('缺少類型')尚未在Roslyn中實現
- 19. 如何在JavaScript中實現此功能?讓不確定,離婚,妻子說!
- 20. 如何將此實用功能轉換爲擴展功能?
- 21. 您是如何在MVVM中成功實現MessageBox.Show()功能的?
- 22. 什麼能在PHP中實現瓶頸cURL的多功能?
- 23. 如何在PHP中實現
- 24. 如何在MVC4中執行此功能?
- 25. 發現使用此功能
- 26. 如何在mysql中實現此查詢
- 27. 如何在SQL中實現此算法?
- 28. 如何在bootstrap中實現此網格?
- 29. 如何在HTML中實現此JavaScript
- 30. iPhone功能:如何重建此功能?