是否可以在PHP中声明静态和非静态方法? [英] Is it possible to declare a method static and nonstatic in PHP?
问题描述
我可以在对象中将方法声明为静态方法还是非静态方法,且其名称与调用静态方法的名称相同?
Can I declare a method in an object as both a static and non-static method with the same name that calls the static method?
我想创建一个类,该类具有一个静态方法"send"和一个调用该静态函数的非静态方法.例如:
I want to create a class that has a static method "send" and a non-static method that calls the static function. For example:
class test {
private $text;
public static function instance() {
return new test();
}
public function setText($text) {
$this->text = $text;
return $this;
}
public function send() {
self::send($this->text);
}
public static function send($text) {
// send something
}
}
我希望能够在这两个函数上调用该函数
I want to be able to call the function on these two was
test::send("Hello World!");
和
test::instance()->setText("Hello World")->send();
有可能吗?
推荐答案
您可以执行此操作,但这有点棘手.您必须通过重载来做到这一点: __call
和__callStatic
魔术方法.
You can do this, but it's a bit tricky. You have to do it with overloading: the __call
and __callStatic
magic methods.
class test {
private $text;
public static function instance() {
return new test();
}
public function setText($text) {
$this->text = $text;
return $this;
}
public function sendObject() {
self::send($this->text);
}
public static function sendText($text) {
// send something
}
public function __call($name, $arguments) {
if ($name === 'send') {
call_user_func(array($this, 'sendObject'));
}
}
public static function __callStatic($name, $arguments) {
if ($name === 'send') {
call_user_func(array('test', 'sendText'), $arguments[0]);
}
}
}
这不是理想的解决方案,因为它会使您的代码难以理解,但是只要您的PHP> = 5.3,它就可以工作.
This isn't an ideal solution, as it makes your code harder to follow, but it will work, provided you have PHP >= 5.3.
这篇关于是否可以在PHP中声明静态和非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!