Heim  >  Artikel  >  Backend-Entwicklung  >  子类使用父类变量解决思路

子类使用父类变量解决思路

WBOY
WBOYOriginal
2016-06-13 10:21:38812Durchsuche

子类使用父类变量
class A {
var $authKey='1111';

}

class B extends A{
 __construct(){
  echo parent::authKey;
}
}
报错Undefined class constant 'authKey'

------解决方案--------------------
错误信息的意思是未定义的常量。你少了个$
但$authKey不是静态变量,所以你不能这么静态调用
正确的做法

PHP code
class A {   // 不建议类中用var来声明变量   public $authKey='1111';}class B extends A{   // B将拥有A的所有非private成员   public function __construct(){      echo $this->authKey;   }}<br><font color="#e78608">------解决方案--------------------</font><br>var 是在php4以前的版本,后来就省略了。<br><font color="#e78608">------解决方案--------------------</font><br>var最好还是视情况带上!有些低版本支持<br><font color="#e78608">------解决方案--------------------</font><br>var 是php 4.X中的,,,5+里使用是为了向下兼容,,<br><br>新写的程序,基本可以放弃这种写法了<br><br>你的代码也可以这样用<br>
PHP code
class A {const authKey='1111';}class B extends A{ public function __construct(){  echo parent::authKey;}}new B;<div class="clear">
                 
              
              
        
            </div>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn