更改基于扩展类的父类方法行为(静态)
问题描述:
我有一个包含各种私有函数的静态类。这些被公共职能调用。我想允许更改其中一个私有函数的选项。无论是使用扩展类还是其他方式。更改基于扩展类的父类方法行为(静态)
这是我这是不工作电流的尝试,但希望证明什么,我想要的目的。
class OriginalClass {
public static function go()
{
self::doThis();
self::doThat();
self::doOther();
}
private static function doThis()
{
echo 'this' . PHP_EOL;
}
private static function doThat()
{
echo 'that' . PHP_EOL;
}
private static function doOther()
{
echo 'default' . PHP_EOL;
}
}
class ExtendedClass extends OriginalClass {
private static function doOther()
{
echo 'other' . PHP_EOL;
}
}
ExtendedClass::go();
我想获得是
this
that
other
,但我发现
this
that
default
我想OriginalClass
能够直接使用,但我想给出能够改变doOther()
所做的选项。我不介意如何,我只是试图保持代码清洁,不做任何事情。
任何想法?
答
doOther
是私人在这两个类的方法。私人方法是不可访问除了类,它们在哪里定义。
因此doOther
的ExtendedClass
上下文不可从OriginalClass
上下文访问。这就是为什么go
方法不能访问ExtendedClass::doOther
,所以它在OriginalClass
其中存在搜索doOther
。
所以,应该做哪些改变:
ExtendedClass::doOther
应至少protected
是availble的在OriginalClass
背景。self
关键字是指OriginalClass
类,使用late static binding获得其要求的方法
class OriginalClass {
public static function go()
{
self::doThis();
self::doThat();
static::doOther(); // keyword `static`
}
private static function doThis()
{
echo 'this' . PHP_EOL;
}
private static function doThat()
{
echo 'that' . PHP_EOL;
}
private static function doOther()
{
echo 'default' . PHP_EOL;
}
}
class ExtendedClass extends OriginalClass {
protected static function doOther() // `protected` visiblity
{
echo 'other' . PHP_EOL;
}
}
ExtendedClass::go();
// output:
// this
// that
// other
OriginalClass::go();
// this
// that
// default
一个真正的类的名称惊人的 - 感谢您的回答和解释! – Steve