Home > Backend Development > PHP Tutorial > 子类使用父类变量解决思路

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

WBOY
Release: 2016-06-13 13:32:22
Original
1032 people have browsed it

子类使用父类变量
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>
Copy after login
PHP code

class A {
const authKey='1111';

}

class B extends A{
 public function __construct(){
  echo parent::authKey;
}
}

new B; <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template