0

Please i need to create a functions and call them in one line using -> between them I have this code but it doesn't run

<?php 
class A {
    public $a2; 
    public $b2; 

    public function mohamed($a){
        $this->a2 =  $a;
        return $this ; 
    }
    public function test($b){
        $this->b2 =  $b;
        return $this ; 
    }
}
$class = new A();
echo $class->mohamed('name')->test('mohamed');;
?>
Qirel
  • 25,449
  • 7
  • 45
  • 62
Mohamed Atef
  • 115
  • 8
  • 1
    People below have worked out your problem, but for future reference, "doesn't run" is not an adequate description of any programming issue. You should tell us the exact error message you receive, and on which line it is thrown, rather than leaving it to people to guess or have to work it out. Make it easy for people to help you, and then you'll find you get even more help! – ADyson Aug 09 '19 at 13:07

4 Answers4

3

Since your class doesn't have a __toString() method, you cannot echo the class object itself.

So you have a few alternatives here, either declare a __toString() method that prints what you want it to, or print the variables separately.

Example using the magic-method __toString() (demo at https://3v4l.org/NPp2L) - you can now echo $class.

public function __tostring() {
    return "A2 is '".$this->a2."' and B2 is '".$this->b2."'";
}

Alternative two is to not print the class itself, but get the properties of the class instead. Since they are public, you don't need a getter-method to use them in the public scope.

$class = new A();
$class->mohamed('name')->test('mohamed');;

echo $class->a2." and ".$class->b2;

Demo at https://3v4l.org/nHeP9

Qirel
  • 25,449
  • 7
  • 45
  • 62
0

If I run your code the error explains the problem :

 Object of class A could not be converted to string

Your function test() returns $this, a class A object which can not be echoed.

Try implement a __toString() function, or use a var_dump() instead of your echo to check your object's properties.

No matter what, your code and your chaining is working fine.

Will
  • 899
  • 8
  • 15
0

Actually, above code is running but you can not echo an object also you can try "var_dump()" instead of "echo".

var_dump($class->mohamed('name')->test('mohamed'));
gzen
  • 1,206
  • 1
  • 8
  • 6
0

Try this:

<?php 
class A {
    public $a2; 
    public $b2; 

    public function mohamed($a){
        $this->a2 =  $a;
        return $this ; 
    }
    public function test($b){
        $this->b2 =  $b;
        return $this ; 
    }
}
$class = new A();
var_dump($class);
?>