开发者

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

开发者 https://www.devze.com 2022-12-20 01:35 出处:网络
If you have a class named \"User\" and another class named \"Admin\" that extends \"User\",开发者_JAVA百科 and you want Admin to inherit all attributes,methods from User, except for the __construct me

If you have a class named "User" and another class named "Admin" that extends "User",开发者_JAVA百科 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?


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.


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.


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

0

精彩评论

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

关注公众号