0

Trying to learn OO PHP but I'm confused on something. I've used frameworks before where they linked together the -> to call multiple functions or variables within those functions.

ex. $variable = $this->query($stmt)->result()->name;

How would you go about setting this up?

class test{
    public $name;
    public function __construct(){      
        $this->name = 'Jon'; // pretending that Jon is a db call result
    }
    public function change_name($n){
        $this->name = $n; 
    }
    public function get_name(){
        return $this->name;
    }
}
$i = new test();

how would I do this? Or is this totally just not possible.

$i->change_name('george')->get_name; // as an example
Sparatan117
  • 138
  • 8
  • possible duplicate of [How do I chain methods in PHP?](http://stackoverflow.com/questions/7549423/how-do-i-chain-methods-in-php) – DCoder Mar 11 '14 at 18:59
  • Duplicate of http://stackoverflow.com/questions/3724112/php-method-chaining – DB---- Mar 11 '14 at 19:00
  • I figured there was probably an answer for it but after googling for hours, I couldn't find what I was looking for. Thanks for the head in the right direction – Sparatan117 Mar 11 '14 at 19:04

3 Answers3

3

When you say "linked", What you really mean is "Chained"

in your example $i->change_name('george')->get_name; // as an example

(!) you have a 2 mistakes

1) ->get_name should be ->get_name() ; // its a function not a property

2) even with ->get_name(), that wont work because it do not have a context.

By example :

When you do : $i->change_name('george') // the method change_name() have the context $i

We continue :

$i->change_name('george')->get_name() // the method get_name() have the context returned by change name, in your case its nothing because your function change_name return nothing 

If we look at your change_name body :

public function change_name($n){
    $this->name = $n; 
}

Nothing is returned, meaning that this function return void or nothing if you prefer.

In your case what you want is to return the object context, the "$this"

try:

public function change_name($n){
    $this->name = $n;
    return $this; 
}

do when you'll do :

$i->change_name('george')->get_name() // the method change_name() have the context returned by change name, now its work

Frederic Nault
  • 986
  • 9
  • 14
1

Return $this from change_name():

public function change_name($n){
    $this->name = $n; 
    return $this;
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

This called method chaining. You can achieve it:

I refer you to this link:

PHP method chaining?

Community
  • 1
  • 1
Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105