Vincent Decaux
Vincent Decaux

Reputation: 10714

PHP return string without "echo"?

I have a class containing a lot of "return" functions :

Class Components_superclass
{
    public function build()
    {
        $this->add_category('Grille');  
    }

    public function add_category($name)
    {
        return '<div class="category">'. $name .'</div>';
    }
    ...
}

I want to get the html code containing in "add_category" function. But when I echo this, I have nothing :

$component = new Components_superclass();
echo $component->build();

Must I add "return" in build function ? Is there a way to avoid this ? Because I have a lot of function to call and I don't want to write something like this :

public function build()
{
     return 
        $this->function_1() .
        $this->function_2() .
        $this->function_3();
}

Thanks !

Upvotes: 1

Views: 3340

Answers (2)

heyarne
heyarne

Reputation: 1167

Yes, the echo doesn't work because nothing is returned from build – there is not string that's passed into echo which could be printed.

About your second question, you could buffer the string internally and then return it at once, like this:

Class Components_superclass
{
    private $buffer = array();

    // …

    public function add_category($name)
    {
        $this->buffer[] = '<div class="category">'. $name .'</div>';
    }

    public function output()
    {
        return implode('', $this->buffer);
    }
}

Upvotes: 2

Ruben
Ruben

Reputation: 343

If you want a function to return a value (that can be a string, integer or other types) use return. If you call the function, the returned value is then available on that place.

If function_1() return the string 'I am function one' and you echo the function call (echo $this->function_1();), the string 'I am function one' will be echoed.

This is also the correct way of working with functions. If you want to echo thing from inside the function, just echo in the function.

Check out PHP.net's function documentation!

Upvotes: 0

Related Questions