开发者

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

开发者 https://www.devze.com 2023-01-12 06:43 出处:网络
The question is in t开发者_高级运维he title.They are non-static by default: public function method() {

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

精彩评论

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