PHP 5: const vs static

前端 未结 7 831
长情又很酷
长情又很酷 2020-11-29 16:38

In PHP 5, what is the difference between using const and static?

When is each appropriate? And what role does public, pr

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 17:32

    Constant is just a constant, i.e. you can't change its value after declaring.

    Static variable is accessible without making an instance of a class and therefore shared between all the instances of a class.

    Also, there can be a static local variable in a function that is declared only once (on the first execution of a function) and can store its value between function calls, example:

    function foo()
    {
       static $numOfCalls = 0;
       $numOfCalls++;
       print("this function has been executed " . $numOfCalls . " times");
    }
    

提交回复
热议问题