gpt4 book ai didi

php - 如何防止在 PHP 的子实例中使用公共(public)父方法?

转载 作者:可可西里 更新时间:2023-11-01 13:17:40 24 4
gpt4 key购买 nike

假设我有名为 parent 和 child 的类,然后将在名为 caller.php 的 PHP 文件中使用它们

class Child extends Parent {

}

class Parent {

public function parentMethod(){

}
}

调用者.php

预防:

$child = new Child();
$child->parentMethod();

允许:

$parent = new Parent();
$parent->parentMethod();

我想防止这样调用 parentMethod。但是,如果我创建了 Parent 对象,我希望能够调用 parentMethod。有什么方法可以隐藏此方法,使其不在子类中公开,但仍允许父对象公开调用此方法?

到目前为止,我想出的唯一解决方案是保护这些方法,然后创建另一个类来扩展父类,然后为它需要的每个函数提供公共(public)方法,但这听起来不是很聪明。

最佳答案

实际上,您应该问问自己:为什么您需要这样的限制?您已将您的方法定义为 public - 因此,您告诉 PHP 它应该随处可见。因此,为了防止子调用,您应该使用 private 可见性定义。

有一种方法可以检查调用是否来自父类,例如:

class ChildClass extends ParentClass {}

class ParentClass
{

public function parentMethod()
{
if(get_class($this) != __CLASS__)
{
throw new LogicException("Somehow due to business logic you're not allowed to call this from childs");
}
}
}

但我不建议这样做。原因是:

  • 可读性。您的方法只是普通的公共(public)方法。看着它,不可能说你是否应该将它用于子调用。因此,要维护此类代码,您需要检查代码中的限制。现在假设您有大约 50 个这样的方法。还有很多这样的类(class)。
  • 可能会破坏 Law of Demeter .为什么在使用这种限制时父类应该知道它的 child ?
  • 最后,这只是意外行为。查看定义,任何人都会看到您正在扩展一个类。因此,根据定义,所有具有适当可见性的继承方法都必须被继承。而你的逻辑改变了这一点。

你可能会想到composition ,不是继承。这可能是实现你的逻辑的正确方法(但是,我不能肯定地说,因为我不知道整个背景)

关于php - 如何防止在 PHP 的子实例中使用公共(public)父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24821932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com