php 类扩展 - 具有相同名称的属性/方法可以吗?

发布于 2024-08-22 09:15:03 字数 487 浏览 4 评论 0原文

例如,如果您有一个名为“User”的类和另一个扩展“User”的名为“Admin”的类,并且您希望 Admin 继承 User 的所有属性和方法,但 __construct 方法除外。

class User {
private $name;

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

class Admin extends User {
private $authorization;

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

这是正确的吗 管理员是否会覆盖用户的构造方法?如果扩展类具有相同的方法名称,我认为它是无效的。 我完全错过了课程扩展的意义吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蘸点软妹酱 2024-08-29 09:15:03

它并不是无效的。类继承的一个方面是,您可以重写方法并提供另一种实现。

但就你而言,我会这样做,

class Admin extends User {
    private $authorization;

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

因为你已经在父类中实现了“名称分配”。这是一种更清洁的方法。

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.

静待花开 2024-08-29 09:15:03

不,这是完全合法的,因为您正在重写 User 的构造函数。一般来说,扩展类中具有相似名称的方法会“覆盖”其父类的方法。

请记住,修饰符确实在这里发挥了作用:超类中声明的“私有”方法不会被覆盖,因为它们不是通过扩展类继承的。 “final”声明的方法在任何情况下都不能通过扩展类来覆盖。

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.

一人独醉 2024-08-29 09:15:03

是的,这就是扩展的目的。
您可以重写所有方法。

您甚至可以在子类的方法内使用相同名称的父类。

请参阅:parent 关键字

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文