Sparatan117
Sparatan117

Reputation: 138

PHP Link Object Operator functions within class

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

Upvotes: 0

Views: 273

Answers (3)

Frederic Nault
Frederic Nault

Reputation: 996

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

Upvotes: 3

AbraCadaver
AbraCadaver

Reputation: 78994

Return $this from change_name():

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

Upvotes: 1

Mostafa Talebi
Mostafa Talebi

Reputation: 9183

This called method chaining. You can achieve it:

I refer you to this link:

PHP method chaining?

Upvotes: 0

Related Questions