【问题标题】:Call to a non static method with out creating an object works fine in PHP调用非静态方法而不创建对象在 PHP 中工作正常
【发布时间】:2015-04-13 11:16:21
【问题描述】:

我正在做一个 PHP 教程,我找到了这段代码

Class Insurance
{
   function clsName()
   {
      echo get_class($this)."\n";
   }
}


$cl = new Insurance();
$cl->clsName();
Insurance::clsName();

此处function clsName() 无需创建Insuarance 实例即可访问

Insurance::clsName();

但从定义上看

范围解析运算符(也称为 Paamayim Nekudotaim)或在 更简单的术语,双冒号,是一个允许访问 类的静态、常量和重写属性或方法。

当从类定义之外引用这些项目时,使用 类的名称。

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

我在网上搜索但找不到很好的解释为什么这段代码有效? 请解释一下。

【问题讨论】:

  • @Rizier123 函数 clsName() 不是静态方法
  • 这应该不起作用,因为clsName() 方法包含对$this 的显式引用,而该引用在静态上下文中不存在
  • 错误报告:<?php ini_set("display_errors", 1); error_reporting(E_ALL); ?> == Strict Standards: Non-static method Insurance::clsName() should not be called statically in C:\xampp\htdocs\Sandbox\index.php on line 30 Notice: Undefined variable: this in C:\xampp\htdocs\Sandbox\index.php on line 23
  • 对非静态方法的静态访问以前可以正常工作(除非方法引用 $this),但在最近的 PHP 版本中已经加强了这一点
  • 对于它们周围的所有花哨的东西,方法仍然只是函数,您可以随心所欲地/在任何地方调用它们。但这并不意味着它们会正确工作。例如调用你的方法会产生错误,因为 $this 在静态调用时不可用。

标签: php function scope-resolution


【解决方案1】:

当我运行它并报告错误时 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_classhttp://php.net/manual/en/function.get-class.php 的行为,则可以识别该类,因为该函数是在该类内部调用的。

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多