【发布时间】:2011-07-12 01:33:25
【问题描述】:
有点难以用 Google 搜索“::”,因为它忽略了符号!
因此,我以一种鲁莽的方式,试图找出 :: 适合 PHP 的位置。
谢谢
【问题讨论】:
标签: php
有点难以用 Google 搜索“::”,因为它忽略了符号!
因此,我以一种鲁莽的方式,试图找出 :: 适合 PHP 的位置。
谢谢
【问题讨论】:
标签: php
:: vs. ->,self vs. $this
对于那些对 :: 和 -> 或 self 和 $this 之间的区别感到困惑的人,我提出以下规则:
如果被引用的变量或方法被声明为 const 或 static,那么您必须使用 :: 运算符。
如果被引用的变量或方法未声明为 const 或 static,则必须使用 -> 运算符。
如果您从类中访问 const 或静态变量或方法,则必须使用自引用 self。
如果您从非 const 或静态类中访问变量或方法,则必须使用自引用变量 $this。
【讨论】:
简单地说,您可以从代码的任何部分调用静态方法或变量,而无需实例化类。为了实现这一点,您使用 ::
这里是帮助您从他们的手册中获得帮助的示例
<?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()
?>
【讨论】:
这意味着静态方法。
Product::get_matching_products($keyword);
这意味着get_matching_products 是Product 上的静态方法
【讨论】:
双冒号是静态方法调用。
这里是静态方法的 PHP 手册页:http://php.net/manual/en/language.oop5.static.php
【讨论】: