简体   繁体   English

如何从父抽象类访问类属性到静态方法?

[英]How to access class properties from parent abstract class to a static method?

Here is a simple example. 这是一个简单的例子。

abstract class A{
  protected $foo = 'I m foo'; 
}

class B extends A{
  static function sayFoo(){
     // get the value of $foo here. 
  }
}

I can pass foo as a constant, or change the function from static to normal, or declare sayFoo inside the parent class but I want to check if there is another way first without using Reflection 我可以将foo作为常量传递,或将函数从静态更改为普通,或在父类中声明sayFoo ,但我想先检查是否有其他方法而不使用Reflection

You can't access the protected $foo property statically because it isn't declared static. 您不能静态访问protected $foo属性,因为它不是静态声明的。 However you could if it was an object. 但是,如果它是一个对象,则可以。 One way to go about this is instantiate the class inside of your static function. 一种解决方法是在静态函数内部实例化类。

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM