我可以将对象中的方法声明为静态方法和非静态方法,并且与调用静态方法的名称相同吗?
我想创建一个具有静态方法“send”和调用静态函数的非静态方法的类。例如:
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
}
}
我希望能够调用这两个函数
test::send("Hello World!");
and
test::instance()->setText("Hello World")->send();
是否可以?
You can这样做,但这有点棘手。你必须通过重载来做到这一点:the __call and __callStatic http://www.php.net/manual/en/language.oop5.overloading.php#object.call魔法方法。
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,它就会起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)