In PHP, what is the best way to print a variable through a function?

2

Let's say I have the following function:

private function teste()
{
    return 'teste';
}

For me to print on the screen, I could simply use:

echo $this->teste();

But in some cases I see that they first assign to a variable and only after that print, as follows:

$variavel = $this->teste();
echo $variavel;

Creating an unnecessary (variable) copy of the function result would not be a waste of processing and memory?

In which cases should we use it directly and assigning it to a variable?

    
asked by anonymous 08.09.2015 / 04:55

3 answers

3
private function teste()
{
    echo 'teste';
}

This method just prints something does not return value, so the following line makes sense

$variavel = $this->teste();

You should change the test method to the following way

private function teste()
{
    return 'teste';
}

And in terms of wasting memory you would be wrong because once the method or function reaches the first return or at the end of your body, all variables that are in its scope would be released from memory. Variables declared within a function are called local variables of the function. To learn more about variable scope.

Depending on the update of the question description , you always assign a value to a variable when you intend to reuse it more than once, or to make the code more readable .

Assigning a variable just to give it more readability would not be memory wasted, because as I said the variables will only be in memory while the context in which it has been declared is being executed (eg a function or method). If it was a few decades ago, the answer would be yes due to hardware limitations, but today that's no problem, readability of the code is more important.

    
08.09.2015 / 05:26
2
private function teste()
{
    echo 'teste';
}

The test method prints a value, and returns nothing, so echo $this->teste() is the same as $this->teste() .

$variavel = $this->teste();
echo $variavel;

In the example above, you print test , but not by echo $variavel , but by method because it contains echo 'teste' . in its example $variavel is null because the method did not return anything.

I made an example in the ideone , you can see the variable as null .

    
08.09.2015 / 05:15
1

Depending on the case, if you just print the value you do not have to make the assignment to a variable. Just echo $this->teste() .

If the return method is used later for a calculation or other operations it makes sense to throw the result into a variable.

$res = $this->teste();
$res = formataAlgo($res);
if($res ...) ...
echo $res;
    
08.09.2015 / 05:31