我正在做一个PHP教程,我发现了以下代码
Class Insurance
{
function clsName()
{
echo get_class($this)."'n";
}
}
$cl = new Insurance();
$cl->clsName();
Insurance::clsName();
这里访问function clsName()
而不创建Insuarance
的实例
Insurance::clsName();
但从的定义来看
范围解析操作员(也称为Paamayim-Nekudotayim)或更简单的术语,双冒号,是一个允许访问类的静态、常量和重写属性或方法。
当从类定义之外引用这些项时,请使用类的名称。
http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php
我在网上搜索了一下,但找不到一个很好的解释,为什么这个代码能工作?请解释。
当我使用错误报告E_ALL:运行它时
Insurance
<br />
<b>Strict Standards</b>: Non-static method Insurance::clsName() should not be called statically in <b>[...][...]</b> on line <b>12</b><br />
<br />
<b>Notice</b>: Undefined variable: this in <b>[...][...]</b> on line <b>5</b><br />
Insurance
现在的问题是为什么它仍然有效?正如你所看到的,显示了"保险"。
当您在静态上下文中调用echo get_class($this)."'n";
时,PHP将像echo get_class(null)."'n";
一样运行它。
如果你读了get_class
的行为http://php.net/manual/en/function.get-class.php,类被识别,因为函数是在类内部调用的。