Examples of access methods for class attributes and class static variables in PHP

墨辰丷
Release: 2023-03-29 10:42:02
Original
2656 people have browsed it

This article mainly introduces the access methods of class attributes and class static variables in PHP, and compares and analyzes the various access techniques of class attributes, static variables and constants in PHP in the form of examples. Friends in need can refer to it

The details are as follows:

<?php
/* PHP类属性与类静态变量的访问
 * Created on 2016-7-13
 */
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();
?>
Copy after login

The running result is: hello world

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Detailed explanation of paging and SqlHelper class usage examples

php Implement common file upload functions

PHP uses strrev to flip Chinese garbled characters with pictures and text. Detailed explanation

The above is the detailed content of Examples of access methods for class attributes and class static variables in PHP. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!