开发者

PHP :: (What does this mean/do?)

Kind of hard to Google "::" as it ignores the symbols!

开发者_开发百科

So in a roustabout way, i'm trying to figure where :: fits into PHP.

Thanks


This means static method.

Product::get_matching_products($keyword);

would mean that get_matching_products is static method on Product


The double-colon is a static method call.

Here's the PHP manual page for static methods: http://php.net/manual/en/language.oop5.static.php

And this tutorial page also has useful information.


In simple way to say it, you can call a static method or variable from any part of your code without instantiating the class. And to achieve that you use ::

here is and example to help you from their manual

<?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()
?> 


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

For people confused about the difference between :: and -> or self and $this, I present the following rules:

If the variable or method being referenced is declared as const or static, then you must use the :: operator.

If the variable or method being referenced is not declared as const or static, then you must use the -> operator.

If you are accessing a const or static variable or method from within a class, then you must use the self-reference self.

If you are accessing a variable or method from within a class that is not const or static, then you must use the self-referencing variable $this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜