To execute the code this way (Method Chaining) it is necessary that your class Customer implement a standard called Fluent Interfaceen.
To be able to do this in PHP it is necessary that the methods of your class to be chained return the instance of itself ($this).
Your class will look like this:
<?php
class Customer {
public function setVat($vat){
// ....
return $this;
}
public function setName($name){
// ...
return $this;
}
public function setLanguageId($languageId){
// ...
return $this;
}
// ...
}
Another way to do this with PHP is by using the magic method __call() together with private setters.
<?php
class Customer {
private function setVat($vat){
// ....
}
private function setName($name){
// ...
}
public function __call($name, $arguments){
if (method_exists($this, $name) && strpos($name, 'set') === 0)
{
$this->$name($arguments[0]); // Tratar o número de argumentos passados é
// uma boa ideia
//$this->$name(...$arguments); // A partir do PHP 5.6
return $this;
}
else
{
throw new Exception('Invalid setter method');
}
}
// ...
}
The public methods of the class would be accessed perfectly, only the setters that are private and are not exposed outside the classes that would enter the __call(). Forcing all setters to go through __call() we don’t need to define the return of $this in all methods.
The strpos($name, 'set') === 0 protects the private methods of our class that do not begin with set, thus preventing undue access to private class methods.
The return is
$this?– Lucas
Post the code of
setVatthat we will see the problem– Lucas
@Lucas you’re right, "Return $this" is missing from the setName() method. Thank you.
– Filipe Moraes