[英]oop - using parent parameters in child/inherited function
I have the following script: 我有以下脚本:
<?php
class A {
protected static $aliases = [];
public static function doSomething()
{
foreach (self::$aliases as $column => $alias) {
// do something
echo "$column: $alias" . PHP_EOL;
}
}
}
class B extends A {
protected static $aliases = [
'id' => 'real_id',
'name' => 'real_name',
];
}
$obj = B::doSomething(); // does nothing
How could I make B inherit the function but use it's own parameters? 如何让B继承函数但使用其自己的参数? I have attempted to create a
getInstance
type function, however I don't think I understood the concept correctly and didn't work. 我试图创建一个
getInstance
类型的函数,但是我认为我没有正确理解该概念,因此无法正常工作。 I have since moved this function into a trait -- it still seems to give the same result. 从那以后,我将此功能转换为特征-它似乎仍然提供相同的结果。
Any and all assistance is appreciated. 任何和所有帮助表示赞赏。
You need to change self::$aliases
to static::$aliases
to refer to B
's aliases within A
. 你需要改变
self::$aliases
,以static::$aliases
指B
的别名内的A
。
See here: https://3v4l.org/h3dP4 看到这里: https : //3v4l.org/h3dP4
<?php
class A {
protected static $aliases = [];
public static function doSomething()
{
foreach (static::$aliases as $column => $alias) {
// do something
echo "$column: $alias" . PHP_EOL;
}
}
}
class B extends A {
protected static $aliases = [
'id' => 'real_id',
'name' => 'real_name',
];
}
$obj = B::doSomething();
This answer does a better job explaining why this works: What is the difference between self::$bar and static::$bar in PHP? 这个答案做得更好,解释了它为什么起作用: 在PHP中self :: $ bar和static :: $ bar有什么区别?
Try using static to access the child property like this 尝试使用static这样访问child属性
public static function doSomething()
{
foreach (static::$aliases as $column => $alias) {
// do something
echo "$column: $alias" . PHP_EOL;
}
}
Take a look http://php.net/manual/en/language.oop5.late-static-bindings.php for better reference 看看http://php.net/manual/en/language.oop5.late-static-bindings.php以获得更好的参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.