Home >Backend Development >PHP Tutorial >关于initialize如何实现

关于initialize如何实现

WBOY
WBOYOriginal
2016-06-23 13:19:241226browse

假设有class a、b、base,a、b都继承base,
a、b允许有一个方法initialize();

如果new N次:
$obj = new a();
$obj = new a();
$obj = new a();
$obj = new b();
$obj = new b();
$obj = new b();

只执行一次 a->initialize(); 和一次 b->initialize(); 

initialize在框架中主要是替代__construct方法。
phalcon实现了这个功能,但是phalcon是C编写的框架,纯PHP能实现这个效果么?


回复讨论(解决方案)

class bass {  function __construct() {    $this->_initialize();  }  function _initialize() {    static $v;    @$v++;    if($v == 1 && method_exists($this, 'initialize')) $this->initialize();  }}class a extends bass {  function initialize() {    echo __CLASS__;  }}class b extends bass {  function initialize() {    echo __CLASS__;  }}$obj = new a();$obj = new a();$obj = new a();$obj = new b();$obj = new b();$obj = new b();
ab

class bass {  function __construct() {    $this->_initialize();  }  function _initialize() {    static $v;    @$v++;    if($v == 1 && method_exists($this, 'initialize')) $this->initialize();  }}class a extends bass {  function initialize() {    echo __CLASS__;  }}class b extends bass {  function initialize() {    echo __CLASS__;  }}$obj = new a();$obj = new a();$obj = new a();$obj = new b();$obj = new b();$obj = new b();
ab


@$v++;
问一下这句为什么要加“@”符合?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn