Your function specifies that it returns a reference to a variable (meaning it does not copy the value, it passes exactly the version that you have inside the function).
Since you return a constant, there is no variable associated with this, so it should not work. PHP is kind though, and interprets what you meant to write as:
private function &getPageByLabel(&$pages, $label){
foreach($pages as &$page){
if($page['label'] == $label) return $page;
}
$return_value = false;
return $return_value;
}
Removing the &
before getPageByLabel
will remove the error, since now you will be returning a (copied) value instead of a reference.
Though note that this may cause your code to malfunction, since you were expecting a reference to one of your $pages
, likely to modify it externally. Without the reference, you will just modify the copy externally and the $page
in $pages
will remain unchanged.
A better way is probably to create a 'dummy object' to return.
You could make a 'dummy page' named $no_page
and return that instead of false
. Then externally you should be able to determine whether or not the page exists by:
$page = $x->getPageByLabel(...);
if ($page === $x->no_page) {
// no page found!
}
A cleaner option is to check for existence first though it is slightly slower:
private function pageExistsWithlabel(&$pages, $label) {
foreach ($pages as $page) {
if ($page['label'] == $label) return true;
}
return false;
}
private function &getPageByLabel(&$pages, $label){
foreach($pages as &$page){
if($page['label'] == $label) return $page;
}
// throw an error here
}
if (! $x->pageExistsWithlabel(...)) {
// handle the case where the page does not exist to prevent the error
} else {
$page = $x->getPageByLabel(...);
}