Example analysis of PHP var keyword related principles and usage

coldplay.xixi
Release: 2023-04-09 07:46:02
forward
2197 people have browsed it

Example analysis of PHP var keyword related principles and usage

I see many friends saying that it doesn’t matter whether you use var or not when defining variables in php, but that’s not the case.

Look at the example, if I use var like this:

var $a=123;
echo $a;
//那么程序会提示语法错误,要去掉var这个变量定义才行。直接
$a=123;
echo $a;
//这样才不会报错,php是弱类型语言,所以不声明类型是没问题的。
Copy after login

When can var be used? Please see:

class Test{
var $a=123;//访问控制,这里的var不用就不正常,当然你可以用public protected等关键词代替,来声明成员变量的属性

}
$obj=new Test();
echo $obj->a;
//打印结果:123
Copy after login

If you change var to public, it will work just as well. .

But at this time, if you remove var in the class and there is no access modifier, it will prompt a syntax error.

In fact, after testing, I believe that var is an alias for public and is used to define public properties in a class. However, due to historical issues, var is no longer used now. Later, I checked the php official website and it turned out to be true.

php official explanation:
Class attributes must be defined as one of public, protected, and private. If defined with var, it is considered public.

Note: For compatibility reasons, the method of defining variables using the var keyword in PHP 4 is still valid in PHP 5 (just as an alias for the public keyword). In versions before PHP 5.1.3, this syntax will generate a E_STRICT Warning

Related learning recommendations: PHP Programming from Beginner to Master

The above is the detailed content of Example analysis of PHP var keyword related principles and usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
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!