PHP类中的static关键词

什么情况下使用static关键字?

如果一个方法与他所在类的实例对象无关,那么它就应该是静态的,而不应该把它写成实例方法。所以所有的实例方法都与实例有关,既然与实例有关,那么创建实例就是必然的步骤,没有麻烦简单一说。

如何使用static关键字?

类中使用:

<?php
class A{
   public static function a1(){
     echo 'this is static function';
   }

   public function a2(){
     echo 'this is dy function';
   }
}

调用:有static的方法,不能使用$this,应该使用A::a1(),self::a1()。

没有static关键字的方法,首先实例化类,然后使用—>a2() 来调用。

注意事项:

static静态方法中,传参不能是表达式。 例如:public static function a1($time=strtotime(“next year”)){} 会报错。$time=null 可以通过。

You May Also Like

About the Author: 萌新

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注