PHP:如果我以非静态方式调用静态方法怎么办 [英] PHP: What if I call a static method in non-static way

查看:295
本文介绍了PHP:如果我以非静态方式调用静态方法怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是面向对象编程的专业人士,但我遇到了一个愚蠢的问题:

I'm not pro in Object Oriented Programming and I got a silly question:

class test {
    public static function doSomething($arg) {
        $foo = 'I ate your ' . $arg;
        return $foo;
    }
}

所以调用doSomething()方法的正确方法是执行test::doSomething('Pizza');,对吗?

So the correct way to call doSomething() method is to do test::doSomething('Pizza');, Am I right?

现在,如果我这样称呼它会发生什么:

Now, what will happen if I call it like this:

$test = new test;
$bar = $test->doSomething('Sandwich');

我已经对其进行了测试,并且可以正常运行,没有任何错误或通知等,但是这样做是否正确?

I've tested it and it's working without any error or notice or etc. but is that correct to do this?

推荐答案

正如Baba所指出的,根据您的配置,它会导致E_STRICT.

As Baba already pointed out, it results in an E_STRICT depending on your configuration.

但是即使您没问题,我也值得一提的是,以非静态方式调用静态方法可能导致的一些陷阱.

But even if that's no problem for you, I think it's worth mentioning some of the pitfalls which may result from calling static methods in a non-static way.

如果您具有类似这样的类层次结构

If you have a class hierarchy like

class A {
    public static function sayHello() {
        echo "Hello from A!\n";
    }

    public function sayHelloNonStaticWithSelf() {
        return self::sayHello();
    }

    public function sayHelloNonStaticWithStatic() {
        return static::sayHello();
    }
}

class B extends A {
    public static function sayHello() {
        echo "Hello from B!\n";
    }

    public function callHelloInMultipleDifferentWays() {
        A::sayHello();
        B::sayHello();
        $this->sayHelloNonStaticWithSelf();
        $this->sayHelloNonStaticWithStatic();
        $this->sayHello();
    }
}

$b = new B();
$b->callHelloInMultipleDifferentWays();

这将产生以下输出:

Hello from A!
// A::sayHello() - obvious

Hello from B!
// B::sayHello() - obvious

Hello from A!
// $this->sayHelloNonStaticWithSelf()
// self alweays refers to the class it is used in

Hello from B!
// $this->sayHelloNonStaticWithStatic()
// static always refers to the class it is called from at runtime

Hello from B!
// $this->sayHello() - obvious

如您所见,在混合静态和非静态方法调用与技术时,很容易实现意外行为.

As you can see, it's easy to achieve unexpected behaviour when mixing static and non-static method calls and techniques.

因此,我的建议也是: 使用 Class :: method 显式调用您要调用的静态方法. 甚至最好不要使用静态方法,因为它们会使您的代码不可测试.

Therefore, my advice also is: Use Class::method to explicitly call the static method you mean to call. Or even better don't use static methods at all because they make your code untestable.

这篇关于PHP:如果我以非静态方式调用静态方法怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆