Inn*_*gen 3 php oop class object method-chaining
可能重复:
PHP方法链接?
我偶尔会看到一些php应用程序使用这样的类:
$Obj = new Obj();
$Obj->selectFile('datafile.ext')->getDATA();
Run Code Online (Sandbox Code Playgroud)
上面的例子获取所选文件的内容然后返回它们(只是一个例子);
好吧,在我决定问你怎么做之前,我试过这个:
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 ....
}
Run Code Online (Sandbox Code Playgroud)
这是完成这项任务的正确方法吗?请告诉我这些课程的名称.
Flu*_*key 11
它被称为方法链.在SO上看看这个问题.
这是一种你可以做你想要实现的方法:
class File
{
protected $_fileName;
public function selectFile($filename)
{
$this->_fileName = $filename;
return $this;
}
public function getData()
{
return file_get_contents($this->_fileName);
}
}
$file = new File();
echo $file->selectFile('hello.txt')->getData();
Run Code Online (Sandbox Code Playgroud)
注意我们$this在selectFile中返回,这使我们能够将另一个方法链接到它上面.