我可以将对象中的方法声明为静态和非静态方法,并且具有调用静态方法的相同名称吗?
我想创建一个具有静态方法"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
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在这两个上调用函数
test::send("Hello World!");
Run Code Online (Sandbox Code Playgroud)
和
test::instance()->setText("Hello World")->send();
Run Code Online (Sandbox Code Playgroud)
可能吗?
lon*_*day 75
你可以做到这一点,但这有点棘手.你有超载做到这一点:在__call和__callStatic魔术方法.
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 function __callStatic($name, $arguments) {
if ($name === 'send') {
call_user_func(array('test', 'sendText'), $arguments[0]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个理想的解决方案,因为它使您的代码更难以遵循,但只要您有PHP> = 5.3,它就可以工作.
| 归档时间: |
|
| 查看次数: |
17464 次 |
| 最近记录: |