Domanda

For my latest website I'm trying to use OOP. I'm using the project to develop my understanding of this technique. Previously I would 'include' a functions folder that contains various php files labelled things like image.upload.functions.php and general.error.handling.functions.php etc.

However, this time I'm using classes wherever possible.

I have just read that in order to use a parents methods (in an extended class) you must run the parents constructor however I haven't done this and my project seems to work ok.

So.. I have a class called Form Validation I have another class called Process Login that extends Form Validation.

My Form Validation class does things like test a password strength to make sure it is strong enough, check whether a user is in the database etc.

I extend Form Validation with a Registration class and a Forgotten Passowrd class.

Should I be putting:

parent::_construct();

..in the constructor of each of the extended classes?

Could someone explain 'simply' the reasons why we do OR do not do this? And whether it's something I should be doing?

Many thanks :-)

È stato utile?

Soluzione

Here's the link to official documentaion: constructors and destructors

And here's the quote:

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. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Calling parent constructor is NOT necessary. And, in general, it is not called implicitly, if You have defined constructor in Your own child class. But, if in the parent constructor You have a nice piece of logic or functionality, that You don't want to lose, then call parent's constructor from the child's one.

Altri suggerimenti

You call parent::__construct() (watch that there are two underscores) if you want to reuse the functionality of the constructor from the class you're extending.

The reuse of code is a main reason for inheritance in OOP. So if there is any algorithm in your parent class that you want to use, you have to call parent::__construct().

If you're extending the parent's constructor, you also have to call it before (or after) your own additions, e.g. like this

class A extends B {
    public __constructor() {
        parent::__construct();
        // Your own code
    }
}

If you don't want to use any of your parents' constructor functions, you don't inherit from that parent constructor - but I assume that in most cases you want to.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top