如何创建类似laravel的类来连续调用类方法



大家好,我的问题是如何编写像laravel这样的类。我认为这种类型的课更容易使用代码示例:

ClassName::method1('value')->method2('value')->method3('value');

如果你注意的方法是使用连续

我在laravel的route部分看到了这种类,所以我对这个类感兴趣,我想在我自己的程序中使用它!

这种装载方式有效吗?

我很乐意举个例子如果你能解释一下

谢谢。

以下示例可能有助于了解方法链接的概念。

方法one()two()three()分别设置一个属性,然后使用return $this返回当前对象。

返回$this(对象(允许方法的链接,因为您可以在返回的对象上调用另一个方法:

<?php
class Movie
{
private string $one = '';
private string $two = '';
private string $three = '';
public function one(): object
{
$this->one = "One ";
return $this; // return object
}
public function two(): object
{
$this->two = "Flew Over the ";
return $this; // return object
}
public function three(): object
{
$this->three = "Cuckoo's Nest";
return $this; // return object
}
public function show(): string
{
return $this->one . $this->two . $this->three;
}
}
$movie = new Movie();
echo $movie->one()->two()->three()->show();

看到它在行动

最新更新