[英]How to access class properties from parent abstract class to a static method?
这是一个简单的例子。
abstract class A{
protected $foo = 'I m foo';
}
class B extends A{
static function sayFoo(){
// get the value of $foo here.
}
}
我可以将foo作为常量传递,或将函数从静态更改为普通,或在父类中声明sayFoo
,但我想先检查是否有其他方法而不使用Reflection
您不能静态访问protected $foo
属性,因为它不是静态声明的。 但是,如果它是一个对象,则可以。 一种解决方法是在静态函数内部实例化类。
<?php
abstract class A{
protected $foo = 'I m foo';
}
class B extends A{
static function sayFoo(){
// get the value of $foo here.
$bar = new self();
echo $bar->foo;
}
}
B::sayFoo(); //prints 'I m foo';
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.