php 类扩展 - 具有相同名称的属性/方法可以吗?
例如,如果您有一个名为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它并不是无效的。类继承的一个方面是,您可以重写方法并提供另一种实现。
但就你而言,我会这样做,
因为你已经在父类中实现了“名称分配”。这是一种更清洁的方法。
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
as you already implement the "name assignment" in the parent class. It is a cleaner approach.
不,这是完全合法的,因为您正在重写 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.
是的,这就是扩展的目的。
您可以重写所有方法。
您甚至可以在子类的方法内使用相同名称的父类。
请参阅:
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