php php静态函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/902909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php static function
提问by Moon
I have a question regarding static function in php.
我有一个关于 php 静态函数的问题。
let's assume that I have a class
让我们假设我有一堂课
class test {
public function sayHi() {
echo 'hi';
}
}
if I do test::sayHi();it works without a problem.
如果我这样做,test::sayHi();它就没有问题。
class test {
public static function sayHi() {
echo 'hi';
}
}
test::sayHi();works as well.
test::sayHi();也有效。
What are the differences between first class and second class?
一等舱和二等舱有什么区别?
What is special about a static function?
静态函数有什么特别之处?
回答by Jonathan Fingland
In the first class, sayHi()is actually an instance method which you are calling as a static method and you get away with it because sayHi()never refers to $this.
在第一个类中,sayHi()实际上是一个实例方法,您将其作为静态方法调用并且您可以使用它,因为sayHi()从不引用$this.
Static functions are associated with the class, not an instance of the class. As such, $thisis not available from a static context ($thisisn't pointing to any object).
静态函数与类相关联,而不是与类的实例相关联。因此,$this在静态上下文中不可用($this不指向任何对象)。
回答by user2132859
Simply, static functions function independently of the class where they belong.
简单地说,静态函数的功能独立于它们所属的类。
$this means, this is an object of this class. It does not apply to static functions.
$this 表示,这是这个类的一个对象。它不适用于静态函数。
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 'Hi'
回答by chaos
Entire difference is, you don't get $thissupplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.
完全不同的是,您不会$this在静态函数内得到提供。如果您尝试使用$this,您将获得一个Fatal error: Using $this when not in object context.
Well, okay, one other difference: an E_STRICTwarning is generated by your first example.
好吧,还有一个区别:E_STRICT您的第一个示例会生成警告。
回答by chaos
Calling non-static methods statically generates an E_STRICT level warning.
静态调用非静态方法会生成 E_STRICT 级别警告。
回答by Czimi
In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.
简而言之,在第二种情况下,您没有 $this 作为对象,因为静态方法是类的函数/方法,而不是对象实例。
回答by yogesh
After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $thisoperator to work on class functions. So I couldn't find a difference in them yet. :(
在尝试示例(PHP 5.3.5)之后,我发现在定义函数的两种情况下,您都不能使用$this运算符来处理类函数。所以我还没有发现它们之间的区别。:(

