本文實例講述了PHP中類屬性與類靜態變量的訪問方法。分享給大家供大家參考,具體如下:
<?php/* PHP類屬性與類靜態變量的訪問 * Created on 2016-7-13 */class test{ const constvar='hello world'; static $staticvar='hello world'; function getStaticvar(){ return self::$staticvar; }}$obj=new test();echo test::constvar; //輸出'hello world'echo @test::staticvar; //出錯,staticvar 前必須加$才能訪問,這是容易和類常量(per-class常量)容易混淆的地方之一echo test::$staticvar; //輸出'hello world'$str='test';//echo $str::$staticvar; //出錯,類名在這不能用變量動態化//echo $str::constvar; //出錯原因同上//在類名稱存在一個變量中處于不確定(動態)狀態時,只能以以下方式訪問類變量$obj2=new $str();echo $obj2->getStaticvar();?>運行結果為:hello world
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選