【问题标题】:Why can I call non-static function without declaring the class object?为什么我可以在不声明类对象的情况下调用非静态函数?
【发布时间】:2015-09-15 11:07:49
【问题描述】:

我使用的是 Symfony 1.0,我的 MyClassInc.class.php 文件夹中有这个 MyClassInc.class.php

class MyClassInc {
  public function validateFunction ($params) {
    // my codes
  }
  static function testFunction ($params){
    // my codes
  }
}

然后,我在project/apps/myapps/modules/actions 中操作actions.class.php

class inventoryCycleCountActions extends sfActions
{
  public function validateOutstandingTransaction () {
    $res0 = MyClassInc :: validateFunction($param); // It works
    $res1 = MyClassInc :: testFunction($param); // It works
    $myClass = new MyClassInc();
    $res2 = $myClass->validateFunction($param); // still works
    $res3 = $myClass->testFunction($param); // still works, da hell?
  }
}

我试图清除我的缓存文件夹以重新测试,但似乎所有这些工作都很好。

问题: 所以为什么?我应该使用哪一个?对性能有什么影响吗?

更新 1:

class MyClassInc {
  public function isProductValidated ($product){
    return true;
  }
  public function validateFunction ($params) {
    // IF, I call by using "$res0".. Throws error
    //
    $this->isProductInLoadPlans($product);
  }
}

如果我通过 $res0 调用 validateFunction,它会抛出这个错误:

sfException: 调用未定义的方法 inventoryCycleCountActions::isProductValidated。

而且,如果我通过 $res2 调用它,它就可以正常工作。

因为,我目前正在使用 $res0,所以我必须像这样调用该方法。

MyClassInc :: isProductValidated ($product)

【问题讨论】:

  • 看看here,基本上,PHP 会警告你(如果你启用了错误报告)。但是,如果您静态调用非静态函数,您将无法访问任何实例变量。因此,如果您尝试使用仅适用于对象的任何变量(即实例变量),您将收到致命错误。
  • 感谢您的回复,戴夫。您所指的线程非常有用,并且感谢我对如何实现我的此类感到更加困惑。使用 :: 调用非静态函数有什么缺点吗?
  • 据我所知,当您静态调用实例方法时,PHP 只会生成一个警告。如果您客观地调用静态方法,则没有错误。所以你可以随时使用->

标签: php apache oop model-view-controller symfony1


【解决方案1】:

::-> 之间唯一真正的区别是 $this 的处理方式。使用::,函数将具有$this,因为它是在调用者的范围内定义的:

class A {

  public function foo() {
    A::bar();
    A::foobar();
  }

  static private function bar() {
     // $this here is the instance of A
  }

  static public function foobar() {
    // Here you can have anything in $this (including NULL)
  }
}

$a = new A;
$a->foo();
$a->foobar(); // $this == $a but bad style
A::foobar(); // $this == NULL

当你想使用实例方法时,你应该使用->,因为这样可以正确解析实例方法(包括继承)。 :: 会一直调用指定类的方法。

我相信现在已经努力强制将静态方法仅作为静态方法调用,而将动态方法仅作为动态方法调用以避免混淆。

【讨论】:

  • 那么,有什么推荐的吗?
  • 如果您的函数是静态的,请使用 ::。如果你的函数不是静态的,使用 ->.
猜你喜欢
  • 2022-01-08
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多