Skip to content
Advertisement

How to call functions within a class like Symfony QueryBuilder

I’m trying to create a PHP class and when I call its functions I want them to be called this way.

$result = $instance->init()->selectAll('user')->where('id = 1');
$result->execute();

class example:

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";
    }
}

Now I want to call it this way:

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

I’ve seen this in PDO and in Symfony QueryBuilder. If there’s a way to do this please tell me. Thanks in advance.

Advertisement

Answer

In order to achieve method chaining you should return $this instead of returning static::$name; as in function getName(). You should also consider making your class properties private or protected in case you use inheritance to avoid modification from outside

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>";

You will get the output as: SELECT name,age FROM users

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement