Php 如何在类(如Symfony QueryBuilder)中调用函数

Php 如何在类(如Symfony QueryBuilder)中调用函数,php,Php,我试图创建一个PHP类,当我调用它的函数时,我希望它们以这种方式被调用 $result = $instance->init()->selectAll('user')->where('id = 1'); $result->execute(); 课堂示例: class user{ public static $name = "test"; public $email; public $last_name; public $

我试图创建一个PHP类,当我调用它的函数时,我希望它们以这种方式被调用

$result = $instance->init()->selectAll('user')->where('id = 1');
$result->execute();
课堂示例:

class user{
    public static $name = "test";
    public $email;
    public $last_name;
    public $first_name;
    public $changed_name;
    
    public function getName(){
        return static::$name;
    }
    
    public function init(){
        static::$name = "John";
    }
}
现在我想这样称呼它:

echo $user->init()->getName();

我在PDO和Symfony QueryBuilder中看到过这一点。如果有办法,请告诉我。提前感谢。

为了实现方法链接,您应该返回$this,而不是返回static::$name;与函数getName()相同。在使用继承避免来自外部

的修改时,还应该考虑将类属性私有化或保护。
class Sql
{
private string $table='';
private array  $select      = [];
private string $queryString = '';

public function table(string $table): Sql
{
    $this->table = $table;
    return $this;
}

public function select(array $select): Sql
{
    $this->select = $select;
    return $this;
}

public function getQueryString(): string
{
    return $this->queryString;
}

public function setQueryString(string $queryString): void
{
    $this->queryString = $queryString;
}

private function buildSelect(array $col=[]): void
{
    if(count($this->select)==0)
    {
        $command = "*";
    } else {
        $command = implode(separator:',',array:$this->select);
    }

    $command = "SELECT ".$command." FROM ".$this->table;
    $this->setQueryString($command);
}

public function get(): string
{
    $this->buildSelect();
    return $this->getQueryString();
    }

}

$sql = new Sql();
$s = $sql->table('users')->select(['name','age'])->get();
echo "<pre>";
print_r($s);
echo "</pre>";
类Sql
{
私有字符串$table='';
专用数组$select=[];
私有字符串$queryString='';
公共函数表(字符串$table):Sql
{
$this->table=$table;
退还$this;
}
公共函数选择(数组$select):Sql
{
$this->select=$select;
退还$this;
}
公共函数getQueryString():字符串
{
返回$this->queryString;
}
公共函数setQueryString(字符串$queryString):无效
{
$this->queryString=$queryString;
}
私有函数buildSelect(数组$col=[]):void
{
如果(计数($this->select)==0)
{
$command=“*”;
}否则{
$command=内爆(分隔符:',数组:$this->select);
}
$command=“从“$this->table中选择“$command.”;
$this->setQueryString($command);
}
公共函数get():字符串
{
$this->buildSelect();
返回$this->getQueryString();
}
}
$sql=newsql();
$s=$sql->table('users')->select(['name','age'])->get();
回声“;
印刷品(港币);;
回声“;

您将得到以下输出:SELECT name,age FROM users

感谢您的帮助,我怀疑这一点。再次感谢。我正在更新答案。这是我为你做的一个例子非常感谢你的努力。