A return
statement is the end of any function. That's why a function is said "to have returned" when it's done doing whatever it needs to do. This isn't unique to OO, but to functions in all programming languages.
What you want to do is:
return $this->author.'<br/>'.$this->bookName.'<br/>';
Here, I'm concatenating all values into one string constant, and return that. This way, I have a single return value, and a single return statement with the desired output.
Like I said, even non-methods (regular functions) can't return more than 1 value - nor can they return less than 1 value:
function aFunction()
{
echo '123';
}
Though lacking an explicit return:
$foo = 'not null';
$foo = aFunction();
var_dump($foo);//null!
the function clearly does return null
, just like in C, a function that needn't return any value, returns void
, or a JavaScript function returns undefined
. The same applies to methods: they return null, implicitly or a single explicit return value.
You could write code like this, too:
function sillyFunction($someArgument = 1)
{
return true;
if ($someArgument < 0)
{
return false;
}
if ($someArgument === 0)
{
return null;
}
return $someArgument%2;
}
This function starts with a return true;
statement. Any code that follows will never be reached, and thus never get executed, because this function has to return something to the caller, who then takes over again. You can't go back to the function and continue what you were doing there. A function is a one-go thing.
Workarounds: Thankfully, objects and arrays are regarded as a single value, so they can be returned from a function, and can contain multiple values. So that's the most common way to somehow get a function to return multiple values. The only, minor downside is that, once the function has returned, you have but a single access point for all these values: the variable to which you assigned the return value:
function foo()
{
return array('foo' => range(1,100), 'bar' => range('A','Z'));
}
$foo = foo();
echo $foo['foo'][1], ' => ', $foo['bar'][1];//echoes 2 => B
In some really rare cases (in the past 10 years, I've needed this ~5 times) you can sort-of return several values using references:
function changeArrayAndReturn(array &$arrayRef)
{
array_push($arrayRef, 'I was added in the function');//alters array
return count($arrayRef);//AND returns int
}
$foo = array();
echo changeArrayAndReturn($foo);//echoes 1
$foo[] = 'I was added outside of the function';
echo changeArrayAndReturn($foo);//echoes 3
var_dump($foo);
//array(I was added in the function, I was added outside of the function, I was added in the function)
But that's dangerous and hard to maintain, so stay away, unless you really can't do it any other way