php const static define 基本用法和区别

const  定义一些在运行时不能被改变的数值。一旦值被改变,则会发生错误。

特性 只能用类名访问。不需要用 $  符号

 1 <?php
 2 class test{
 3     const pi=123.12321121;    
 4     public  function run(){
 5         echo self::pi;
 6     }
 7 }
 8 test::pi=123;
 9 echo test::pi;
10 //Parse error: syntax error, unexpected '=' 
 1 <?php
//正常的const 用法。
2 class test{ 3 const pi=123.12321121; 4 public function run(){ 5 echo self::pi; 6 } 7 } 8 9 $test = new test(); 10 $test->run(); 11 echo "<br>"; 12 echo test::pi; 13 14 //结果 15 123.12321121 16 123.12321121

define()

可以用 define() 函数来定义常量。一个常量一旦被定义,就不能再改变或者取消定义。

defind() 不能在类中使用,   define定义变量为全局变量, 在任何地方可以呗访问

用法:

1 <?php
2 define("CONSTANT", "Hello world.");
3 echo CONSTANT; // outputs "Hello world."

define()  定义的时候 不会分配内存空间。 当你定  CONSTANT = Hello world 时, 编译代码时会进行替换  CONSTANT会替换成 hellow world .

Static

php作用域方位内的一个重要的静态属性。在局部函数域中存在 只能被初始化一次。  

不需要实例化类就可以访问。访问方式   类名::$属性名。   必须要有$符号。

类内访问必须用 self::$abc;

 1 <?php
 2 class test{
 3     static $abc=123;
 4     public static function run(){
 5         echo self::$abc;
 6     }
 7 }
 8 
 9 $test = new test();
10 $test->run();
11 echo "<br>";
12 echo test::$abc;
13 
14 //结果
15 123
16 123
原文地址:https://www.cnblogs.com/yhl664123701/p/5477371.html