gpt4 book ai didi

php - 在 PHP 中不推荐在类内部调用非静态方法?

转载 作者:行者123 更新时间:2023-12-03 20:32:52 25 4
gpt4 key购买 nike

如 PHP 手册所述

As of PHP 7.0.0 calling a non-static method statically has been generally deprecated (even if called from a compatible context).

检查这个语句-

我在类外调用一个非静态方法然后它产生错误

class A{
public function foo(){
echo "testing<br/>";
}
}
A::foo();

Deprecated: Non-static method A::foo() should not be called statically

但是当我在一个类中调用一个非静态方法时,它不会生成Deprecated error

class A{
public function foo(){
echo "testing<br/>";
}

public function Display(){
A::foo(); //calling a Non-static method inside statically
self::foo(); //calling a Non-static method inside statically
}
}
$obj=new A();
$obj->Display();

它是否仅在从类外部静态调用时才被弃用?

最佳答案

范围解析运算符或双冒号运算符不仅用于静态调用。

在一个类中,运算符可用于以非静态方式引用类本身。

这就是你为 self::foo() 和 A::foo() 所做的; 要在类内进行静态调用,您需要使用 static::<methodName>声明

看这里:http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

关于php - 在 PHP 中不推荐在类内部调用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47694982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com