我正在使用 Symfony 1.0,我的 project/lib
文件夹中有这个 MyClassInc.class.php
class MyClassInc {
public function validateFunction ($params) {
// my codes
}
static function testFunction ($params){
// my codes
}
}
然后,我的操作 actions.class.php
在我的 project/apps/myapps/modules/actions
中。
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: Call to undefined method inventoryCycleCountActions::isProductValidated.
而且,如果我通过 $res2 调用它,它工作得很好。
因为,我目前正在使用 $res0,所以我必须改为调用该方法。
MyClassInc :: isProductValidated ($product)
最佳答案
::
和 ->
之间唯一真正的区别是 $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
当你想使用实例方法时,你应该使用 ->
因为这样可以正确解析实例方法(包括继承)。 ::
将始终调用指定类的方法。
我相信现在已经做出努力来强制只调用静态方法作为静态方法,而只调用动态方法以避免混淆。
关于php - 为什么我可以在不声明类对象的情况下调用非静态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108012/