开发者

How do you declare a method as public but non-static in PHP?

The question is in t开发者_高级运维he title.


They are non-static by default:

public function method() {

}

You will get an E_STRICT if you call it statically, but I don't think you can easily enforce that it can only be called on an instance - if you try to check $this I think you will get an error. You could do isset($this) as Artefacto says and throw an exception if it isn't set.


<?php
class abc() {

 public function foo() {
     ...
 }
}

$c = new abc();
$c->foo();
?>


<?php
class abc() {

 public function foo() {
     if (!isset($this)) {
         throw new Exception('Method is non-static.');
         exit();
     }
 }
}

$c = new abc();
$c->foo();
?>

Not tested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜