PHP中的Contruct方法类之前和之后

时间:2014-04-12 06:14:08

标签: php

厨师看起来像这样:

abstract class Foo
{
     pulbic function __construct()
     { 
          if (method_exists($this, 'beforeConstruct')) {
              $this->beforeConstruct();
          }

      if (method_exists($this, 'afterConstruct')) {
          $this->afterConstruct();
      }
     }
}

class Bar extends Foo
{
    public function beforeConstruct()
    {
        echo 'Before Construct.<br>';
    }

    public function __construct()
    {
        echo 'Clas Bar has been created.<br>'
    }

    public function beforeConstruct()
    {
        echo 'After Construct.<br>';
    }
}

$bar = new Bar();

但没有工作,有人可以帮助我吗?如何返回这样的结果:

施工前。

已经创建了Class Bar。

构造后。

1 个答案:

答案 0 :(得分:0)

首先从子类constructor调用constructor,后者又调用子类的方法beforeConstruct(),然后调用它在它激发你的子类的Clas Bar has been created.之后打印destructor

<?php

abstract class Foo
{
public function __construct()
{
    if (method_exists($this, 'beforeConstruct')) {
        $this->beforeConstruct();
    }

    if (method_exists($this, 'afterConstruct')) {
        $this->afterConstruct();
    }
}
}

class Bar extends Foo
{
     public function __construct()
    {
        parent::__construct();
        echo 'Clas Bar has been created.<br>';

    }

    public function beforeConstruct()
    {
        echo 'Before Construct.<br>';
    }


    public function __destruct()
    {
        echo 'After Construct.<br>';
    }
}

$bar = new Bar();

<强> OUTPUT:

Before Construct.
Clas Bar has been created.
After Construct.