php 中的公共静态和公共函数有什么区别?

use*_*747 -2 php

我知道根据this有很多信息,但我找不到任何真正有用和可以理解的信息。那么public static function和之间有什么区别public function?为什么有时我必须使用这个词static

我知道静态函数由::和非静态函数调用->,但真正的区别(为什么有时我应该使用static我不明白)。据我所知,当我使用 时static,我可以从另一个类调用它。没有它 - 我不能。但我很确定我错了。

我认为这些信息对很多人真的很有帮助。感谢您花时间尝试解释它。

Cha*_*mar 9

静态意味着可以在不实例化类的情况下访问它。这对常量有好处。

静态方法不需要对对象的状态产生影响。除了参数之外,它们还可以有局部变量。

公共:公共声明的项目可以在任何地方访问。

例子:

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'hello'
Run Code Online (Sandbox Code Playgroud)

更多信息:

http://php.net/manual/en/language.oop5.visibility.php