使用双冒号(::)调用非静态方法 [英] Calling non-static method with double-colon(::)

查看:46
本文介绍了使用双冒号(::)调用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用具有方法 static(class::method) 语法的非静态方法?这是某种配置问题吗?

Why can't I use a method non-static with the syntax of the methods static(class::method) ? Is it some kind of configuration issue?

class Teste {

    public function fun1() {
        echo 'fun1';
    }
    public static function fun2() {
        echo "static fun2" ;
    }
}

Teste::fun1(); // why?
Teste::fun2(); //ok - is a static method

推荐答案

PHP 在静态与非静态方法方面非常松散.我在这里没有看到的一件事是,如果您从 C, 类的非静态方法中静态调用非静态方法 nsns 中的 $this 将引用您的 C 实例.

PHP is very loose with static vs. non-static methods. One thing I don't see noted here is that if you call a non-static method, ns statically from within a non-static method of class C, $this inside ns will refer to your instance of C.

class A 
{
    public function test()
    {
        echo $this->name;
    }
}

class C 
{
     public function q()
     {
         $this->name = 'hello';
         A::test();
     }
}

$c = new C;
$c->q();// prints hello

如果您有严格的错误报告,这实际上是某种错误,否则不是.

This is actually an error of some kind if you have strict error reporting on, but not otherwise.

这篇关于使用双冒号(::)调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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