开发者

is there a __construct() equivalent for extended classes

开发者 https://www.devze.com 2022-12-14 08:09 出处:网络
I have a parent class: Abstract Class Base { function __construct($registry) { // stuff } } I then have at least 2 classes that extend that class

I have a parent class:

Abstract Class Base {
    function __construct($registry) {
        // stuff
    }
}

I then have at least 2 classes that extend that class

class Cms extends Base {
   // a few functions here
}

and this one

class Index extends Base {
   // a few functions here
}

For the CMS class, the user will need to be logged in. Session has already been initiated and I want to check that the user is logged in by using a session 开发者_运维问答var. So what I'd like to do is:

class Cms extends Base {
   function __construct()
   {
        // check the user session is valid
   }
   // a few functions here
}

but of course that will overwrite the parent construct class and everything it set. Is there a way to have a __construct() type method that can be defined in the child class?


From the child constructor, you can call the parent's one :

class Cms extends Base {
   function __construct()
   {
       parent::__construct();
        // check the user session is valid
   }
   // a few functions here
}

See the examples on the Constructors and Destructors page of the manual, and the note (quoting) :

Note: Parent constructors are not called implicitly if the child class defines a constructor.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.


The invocation of a class' constructor doesn't bubble up automagically in php. You have to add a call to the parent's constructor manually. (And I consider that a flaw.)

class Cms extends Base {
   function __construct()
   {
       parent::__construct(); 
       // check the user session is valid
   }
   // a few functions here
}

PHP: Scope Resolution Operator (::) says:

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.


This solution also applies to all php magic methods when dealing with class extensions, ie if you override __set(), you can use the same code (parent::__method) to ensure you get all of the behavior also specified in the parent class.

VolkerK: Why would this be a flaw? The assumption would appear to be that if you are overriding the base classes behavior for a method, that you want to replace that behavior, unless you specifically declare otherwise. I would find it very distressing if I could extend a method, but always called the default behavior in the parent class, as well as whatever I was doing. Do other OO languages implement it that way?

0

精彩评论

暂无评论...
验证码 换一张
取 消