gpt4 book ai didi

PHP静态方法

转载 作者:可可西里 更新时间:2023-11-01 13:27:26 24 4
gpt4 key购买 nike

我知道静态方法无法访问其类类型的实例对象的状态,因此在其中引用 $this 会导致错误。但是对象可以使用对象到成员运算符来引用静态方法->

$obj->staticMethod();

甚至可以通过参数传递它们的状态。

$para1 = $obj->para1;

$para2 = $obj->para2;

$obj->staticMethod($para1, $para2);

当在静态上下文中解析静态时,最后一个示例如何可能。如果有人可以向我解释 php 代码中静态的一般行为。如果有帮助,您甚至可以讨论与 C 相关的概念。

最佳答案

既然您说您已经了解static 的含义,那么我将跳过它。

但是,引用 PHP 的 documentation on the static keyword 可能还是不错的.特别是以下两个警报很重要(实际上很难一目了然)。

Caution    In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

还有这个(斜体强调我的)。

Warning     In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

所以,长话短说:是的,您的示例将会运行(暂时),因为 PHP 解释器会尝试为您纠正您的错误。但是,您应该永远不要这样做。 PHP 解释器将做的是:

假设您的$objFoo 类型。然后它会读取

$obj->staticMethod($para1, $para2);

断定 staticMethodstatic 并改为执行

Foo::staticMethod($para1, $para2);

当然,传递作为 Foo 实例属性的参数是完全没问题的。 staticMethod 参数从哪里来并不重要。


为了更详细地说明为什么这样做,在 static 方法中使用 $this 是不允许的。

您可以将普通方法视为具有一个额外功能的static 函数:它们接收一个隐式参数$this$this 的值只是调用该方法的对象。因此,$obj->do($a, $b, $c) 等同于调用 Foo::do($obj, $a, $b, $c) 并将 do 的第一个参数命名为 $this。这很方便,因为我们现在可以轻松地定义在对象实例上工作的方法,而不必一遍又一遍地显式声明该实例是我们方法的参数。太好了。

现在回到static 函数。与普通方法的唯一区别是它们不接收此隐式 $this 参数。因此,在它们内部使用 $this 是无效的。不是因为它被禁止,而是因为它没有引用任何东西。 PHP 没有(也不能)知道 $this 应该引用什么。

另一种看待它的方式。假设我们的 Foo 类有两个属性:$para1$para2,都是数字。假设您编写了一个方法来返回这些数字的总和。一种方法是这样做:

public static function sum($para1, $para2) {
return $para1 + $para2;
}

太棒了。作品。然而,不得不这样调用它很烦人

$sum = Foo::sum($obj->para1, $obj->para2);

所以,这就是方法的用途!

public function sum(/* implicit $this parameter */) {
// write looking up the properties once inside the function, instead
// of having to write it every time we call the function!
return $this->para1 + $this->para2;
}

// ...

$sum = $obj->sum(); // $obj is passed implicitly as $this

因为静态函数不接收隐式的 $this 参数,在它们内部使用 $this 就像尝试使用 $undefined 时你从未定义过它。因此,无效。

关于PHP静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631821/

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