【问题标题】:Using static in PHP [duplicate]在 PHP 中使用静态 [重复]
【发布时间】:2011-09-12 10:23:33
【问题描述】:

可能重复:
PHP: Static and non Static functions and Objects

为什么我要在php中使用static关键字?它只是为了创建“好的”代码还是它也有一些优势?

function useThisAsStatic(){}

static function useThisAsStatic(){}

public static function useThisAsStatic(){}

public function useThisAsStatic(){}

澄清问题;以上方法都可以调用

Object::useThisAsStatic();

因此表明将方法声明为静态没有区别。

【问题讨论】:

标签: php syntax


【解决方案1】:

是否只是为了创建“好”的代码

其实是在写坏代码。
Read why
而this article 更详细地说明了static(感谢 Gordon)

【讨论】:

    【解决方案2】:

    静态函数意味着您可以在不先实例化类(创建对象)的情况下调用它们。

    在某些情况下很有用,但静态函数不能利用该函数之外的类的本地成员。

    【讨论】:

      【解决方案3】:

      static 表示属于该类。您可以调用静态方法或字段。无需创建类的实例。

      【讨论】:

        【解决方案4】:
        class NewClass {
            public $public_var = "I'm public property!";
            public static $static_var = "I'm static property!";
        
            public function public_method()
            {
                return "I'm public method!";
            }
        
            public static function static_method()
            {
                return "I'm static method!";
            }
        }
        

        现在您可以在不创建 NewClass 实例的情况下调用 NewClass::$static_var 和 NewClass::static_method()。 在调用 public_var 和 public_method 时,您应该创建类的新实例:

        $c = new NewClass();
        echo $c->public_var;
        echo $c->public_method();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-25
          • 1970-01-01
          • 2011-02-23
          • 1970-01-01
          相关资源
          最近更新 更多