Static variables in PHP

前端 未结 5 1364
你的背包
你的背包 2020-12-16 09:20

I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.

I have read that when us

5条回答
  •  春和景丽
    2020-12-16 09:57

    class Student {
    static $total_student = 0;
    static  function add_student(){
        return Student::$total_student++;
    }
    }
    

    First: for the add_student function, the best practice is to use static not public. Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable. Third:static variable are shared throughout the inheritance tree.

    take below code to see what is the result:

    class One {
    static $foo ;
    }
    class Two extends One{}
    class Three extends One{}
    One::$foo = 1;
    Two::$foo = 2;
    Three::$foo = 3;
    echo One::$foo;
    echo Two::$foo;
    echo Three::$foo;`
    

提交回复
热议问题