Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

php - PHPUnit - Use $this or self for static methods?

I don't want to write a long text, because it is a short question. PHPUnit tests contain several methods that are static. For example all those PHPUnitFrameworkAssert::assert*() methods and also the identicalTo, equalTo.

My IDE (with IntelliSense/autocompletion) doesn't accept calls with $this, but with self. I have learned that static functions should be called through the class, not an object, so self.

What is more correct?

$this->assertTrue('test');

or

self::assertTrue('test');

?

(And if "$this" is more correct, can you maybe point out why we should not use "self"?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally, self is only used to refer to static methods and properties (though confusingly you can refer to non-static methods with self, and to static methods with $this, provided the methods called with self don't reference $this.)

<?php
class Test {
    public static function staticFunc() {echo "static ";}
    public function nonStaticFunc() {echo "non-static
";}
    public function selfCaller() {self::staticFunc(); self::nonStaticFunc();}
    public function thisCaller() {$this->staticFunc(); $this->nonStaticFunc();}
}
$t = new Test;
$t->selfCaller();  // returns "static non-static"
$t->thisCaller();  // also returns "static non-static"

Inheritance is important to remember when dealing with $this or self. $this will always refer to the current object, while self refers to the class in which self was used. Modern PHP also includes late static binding via the static keyword, which will operates the same way as (and should be preferred over) $this for static functions.

<?php
class Person {
    public static function whatAmI() {return "Human";}    
    public function saySelf() {printf("I am %s
", self::whatAmI());}
    public function sayThis() {printf("I am %s
", $this->whatAmI());}
    public function sayStatic() {printf("I am %s
", static::whatAmI());}
}

class Male extends Person {
    public static function whatAmI() {return "Male";}
}

$p = new Male;
$p->saySelf();    // returns "I am Human"
$p->sayThis();    // returns "I am Male"
$p->sayStatic();  // returns "I am Male"

As regards PHPUnit in particular, it appears they simply do things the way they've always done them! Though according to their documentation, your code should work fine using static methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...