Jump to content

PHP Objects and Methods question


milesap

Recommended Posts

I've seen some people code with objects in PHP, but one thing that others do (that I'd like to do) is the ability to call multiple methods at once. For example, in Zend Framework it's possible to write the following:

 

$variable->setMessage('Text')->addColor('blue')->toArray(); (just an example)

 

Notice how you can call several methods at once without having to write $variable next to each method? I've tried to do similar stuff in my code but cannot achieve this effect. Does anyone know how to set this up or point me in the right direction? Thanks!

Link to comment
https://forums.phpfreaks.com/topic/208180-php-objects-and-methods-question/
Share on other sites

Hi,

 

Its a great question  ;D and exciting at all.

 

Heres a simple example what im just done:

 

class class_a extends class_b
{
    public function func_a()
    {
        echo 'm';

        return $this;
    }
}

class class_b
{
    public function func_b()
    {
        echo 'n';
    }
}

$a = new class_a();

$a->func_a()->func_b();

 

Hi,

 

Its a great question  ;D and exciting at all.

 

Heres a simple example what im just done:

 

class class_a extends class_b
{
    public function func_a()
    {
        echo 'm';

        return $this;
    }
}

class class_b
{
    public function func_b()
    {
        echo 'n';
    }
}

$a = new class_a();

$a->func_a()->func_b();

 

Excellent! So all subsequent methods must be extensions of the last method called, makes a lot of sense when trying to build easy to read, flexible code. Thanks for your help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.