【问题标题】:PHP :: (What does this mean/do?)PHP ::(这是什么意思/做什么?)
【发布时间】:2011-07-12 01:33:25
【问题描述】:

有点难以用 Google 搜索“::”,因为它忽略了符号!

因此,我以一种鲁莽的方式,试图找出 :: 适合 PHP 的位置。

谢谢

【问题讨论】:

标签: php


【解决方案1】:

:: vs. ->,self vs. $this

对于那些对 ::->self$this 之间的区别感到困惑的人,我提出以下规则:

如果被引用的变量或方法被声明为 const 或 static,那么您必须使用 :: 运算符。

如果被引用的变量或方法未声明为 const 或 static,则必须使用 -> 运算符。

如果您从类中访问 c​​onst 或静态变量或方法,则必须使用自引用 self

如果您从非 const 或静态类中访问变量或方法,则必须使用自引用变量 $this

【讨论】:

    【解决方案2】:

    简单地说,您可以从代码的任何部分调用静态方法或变量,而无需实例化类。为了实现这一点,您使用 ::

    这里是帮助您从他们的手册中获得帮助的示例

    <?php
    function Demonstration()
    {
        return 'This is the result of demonstration()';
    }
    
    class MyStaticClass
    {
        //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
        public static $MyStaticVar = null;
    
        public static function MyStaticInit()
        {
            //this is the static constructor
            //because in a function, everything is allowed, including initializing using other functions
    
            self::$MyStaticVar = Demonstration();
        }
    } MyStaticClass::MyStaticInit(); //Call the static constructor
    
    echo MyStaticClass::$MyStaticVar;
    //This is the result of demonstration()
    ?> 
    

    【讨论】:

      【解决方案3】:

      这意味着静态方法。

      Product::get_matching_products($keyword);
      

      这意味着get_matching_productsProduct 上的静态方法

      【讨论】:

        【解决方案4】:

        双冒号是静态方法调用。

        这里是静态方法的 PHP 手册页:http://php.net/manual/en/language.oop5.static.php

        还有this tutorial page also has useful information

        【讨论】:

          猜你喜欢
          • 2014-09-01
          • 2014-04-03
          • 1970-01-01
          • 1970-01-01
          • 2013-08-17
          • 2011-09-04
          相关资源
          最近更新 更多