Home  >  Article  >  Backend Development  >  PHP Class Attributes Access to Class Static Variables_PHP Tutorial

PHP Class Attributes Access to Class Static Variables_PHP Tutorial

WBOY
WBOYOriginal
2016-07-14 10:12:04995browse

There are actually two types of class attributes in PHP, one is class constant and the other is class static variable. Both are easily confusing.

Like static class methods and class instance methods, static class attributes and instance attributes cannot be redefined (have the same name), but static attributes can have the same name as class constants.

<?php 
class test 
{ 
  const constvar=&#39;hello world&#39;; 
  static $staticvar=&#39;hello world&#39;; 
  function getStaticvar(){ 
     return self::$staticvar; 
  } 
} 
 
$obj=new test(); 
echo test::constvar //输出&#39;hello world&#39; 
echo test::staticvar //出错,staticvar 前必须加$才能访问,这是容易和类常量(per-class常量)容易混淆的地方之一 
echo test::$staticvar //输出&#39;hello world&#39; 
$str=&#39;test&#39;; 
echo $str::$staticvar //出错,类名在这不能用变量动态化 
echo $str::constvar //出错原因同上 
 
//在类名称存在一个变量中处于不确定(动态)状态时,只能以以下方式访问类变量 
$obj2=new $str(); 
echo $obj2->getStaticvar(); 
?> 

<?php
class test
{
  const constvar=&#39;hello world&#39;;
  static $staticvar=&#39;hello world&#39;;
  function getStaticvar(){
     return self::$staticvar;
  }
}

$obj=new test();
echo test::constvar //输出&#39;hello world&#39;
echo test::staticvar //出错,staticvar 前必须加$才能访问,这是容易和类常量(per-class常量)容易混淆的地方之一
echo test::$staticvar //输出&#39;hello world&#39;
$str=&#39;test&#39;;
echo $str::$staticvar //出错,类名在这不能用变量动态化
echo $str::constvar //出错原因同上

//在类名称存在一个变量中处于不确定(动态)状态时,只能以以下方式访问类变量
$obj2=new $str();
echo $obj2->getStaticvar();
?>

 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477225.htmlTechArticleThere are actually two types of class attributes in PHP, one is class constant and the other is class static variable. Both are easily confusing. Just like static class methods and class instance methods, static class properties and instance properties...
Statement:
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