PHP 静态方法与实例方法 [英] PHP static method vs instance method

查看:58
本文介绍了PHP 静态方法与实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中有以下代码.在 Phpunit 和 Laravel 中进行测试.为什么类方法与实例方法相同?我期待调用 $instance->classMethod() 会返回一些错误.这是否也意味着实例方法名称不应由类方法名称共享?还是 php 中的静态方法"与我对类方法"的理解不同?

I have the following code in PHP. Testing in Phpunit and Laravel. Why is class method the same as instance method? I was expecting calling $instance->classMethod() would return some error. Does this also mean that instance method name shouldn't be shared by class method names? Or is 'static method' in php different from my understanding of a 'class method'?

<?php
class DemoClass{
    static function classMethod(){
        return "i'm a class method";
    }
}

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $instance = new DemoClass;
        $result1 = $instance->classMethod();
        $result2 = DemoClass::classmethod();

        $this->assertNotEquals($result1, $result2);
    }

}

结果:

断言我是一个类方法"不等于<string:我是一个类方法>失败.

推荐答案

PHP 是一种非常灵活的语言.您可以通过多种方式调用静态方法,其中 2 种方法已在 $object->staticmethod()$object::staticMethod() 上方显示.从 $this 或对象实例调用静态方法是完全合法的.

PHP is a very flexible language. There are many ways you can call static methods, 2 methods of which you have displayed above $object->staticmethod() or $object::staticMethod(). It is perfectly legal to call static methods from $this or the object instance.

另一种调用静态/普通方法的方法是使用像 call_user_func 这样的函数.此处存在现有讨论:

Another way to call static/normal methods is using functions like call_user_func. An existing discussion exists over here:

PHP 中的静态方法

这篇关于PHP 静态方法与实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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