PHP:链接方法调用
可能的重复:
PHP 方法链接?
我偶尔会看到一些 php 应用程序使用这样的类:
$Obj = new Obj();
$Obj->selectFile('datafile.ext')->getDATA();
上面的示例获取以下内容然后所选文件返回它们(仅是一个示例);
好吧,在我决定问你如何做到这一点之前,我尝试过:
class Someclass {
public function selectFile( $filename ) {
$callAclass = new AnotherClass( $filename );
return $callAclass;
}
// Other functions ...
}
class AnotherClass {
protected $file_name;
public function __construct ( $filename ) { $this->file_name = $filename; }
public function getDATA ( ) {
$data = file_get_contents( $this->file_name );
return $data;
}
// funcs , funcs, funcs ....
}
这是完成这项任务的正确方法吗?请告诉我这些类的名称。
Possible Duplicate:
PHP method chaining?
I occasionally see some php applications use classes like that:
$Obj = new Obj();
$Obj->selectFile('datafile.ext')->getDATA();
The example above gets the contents of the selected file then returns them ( just an example );
Well, before i decided to ask you how can I do this, I tried this:
class Someclass {
public function selectFile( $filename ) {
$callAclass = new AnotherClass( $filename );
return $callAclass;
}
// Other functions ...
}
class AnotherClass {
protected $file_name;
public function __construct ( $filename ) { $this->file_name = $filename; }
public function getDATA ( ) {
$data = file_get_contents( $this->file_name );
return $data;
}
// funcs , funcs, funcs ....
}
Is that the right way to accomplish this task? And please tell me what these classes are called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这称为方法链。看看这个问题。
您可以通过以下方式实现您想要实现的目标:
请注意,我们在 selectFile 中返回
$this
,这使我们能够将另一个方法链接到它上面。It's called method chaining. Have a look at this question on SO.
Here's a way you can do what you're trying to achieve:
Notice we return
$this
in the selectFile, this enables us to chain another method onto it.上面的例子(第一个)就是所谓的链接。这是一个常规类:
您可以这样称呼它们:
这将回显“方法 a - 方法 b”。现在要链接它们,您将在方法中返回对象:
您将像这样调用它们:
这也会回显“方法 a - 方法 b”。
尽管我在最后一个方法中返回了对象 - 您严格意义上不需要这样做,只有前面的方法需要它来进行链接。
The above example (the first one) is something called chaining. Here's a regular class:
You'd call those like this:
Which would echo 'method a - method b'. Now to chain them, you'd return the object in the methods:
You'd call those like this:
Which would also echo 'method a - method b'.
Although I have returned the object in the last method - you strictly wouldn't need to, only the preceding methods require that for chaining.