简体   繁体   English

如何在PHP中将方法声明为公共但非静态?

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

问题出在标题中。

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. 如果你静态地调用它,你将得到一个E_STRICT ,但我认为你不能轻易地强制它只能在一个实例上调用 - 如果你试图检查 $this我认为你会得到一个错误。 You could do isset($this) as Artefacto says and throw an exception if it isn't set. 您可以按照Artefacto的说法进行isset($this) ,如果未设置则抛出异常。

<?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. 没有测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM