Gal
Gal

Reputation: 23662

php class extends - attributes/methods with same name ok?

If you have a class named "User" and another class named "Admin" that extends "User", and you want Admin to inherit all attributes,methods from User, except for the __construct method, for example.

class User {
private $name;

function __construct($name) {
$this->name = $name;
}
}

and

class Admin extends User {
private $authorization;

function __construct($name,$authorization) {
$this->name = $name;
$this->authorization = $authorization;
}
}

Is this correct? Does Admin override User's construct method? If the extending class has the same method name I suppose it's invalid. Am I totally missing the point of class extension?

Upvotes: 4

Views: 7122

Answers (3)

skyman
skyman

Reputation: 2472

Yes it's what extends is for. You can override all methods.

You can even use same named parent class inside method in child class.

See: parent keyword

Upvotes: 1

aefxx
aefxx

Reputation: 25289

No, this is perfectly legal as you are overriding User's constructor. Generally spoken, methods with similar names in extending class "override" their parent's.

Keep in mind though that modifiers do play a role here: "private" declared methods in a superclass won't get overridden as they aren't inherited by extending classes. "final" declared methods can't be overriden by extending classes - under no circumstances.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817228

It is not invalid. One aspect of class inheritance is, that you can override methods and provide another implementation.

But in your case, I would do

class Admin extends User {
    private $authorization;

    function __construct($name,$authorization) {
        parent::__construct($name);
        $this->authorization = $authorization;
    }
}

as you already implement the "name assignment" in the parent class. It is a cleaner approach.

Upvotes: 8

Related Questions