The above code will work only when page object has configured url. When that does not happen the code will not serve. This function covers that case as well:
/**
* @return bool
* @throws Exception
* @throws dml_exception
*/
function is_homepage() {
global $PAGE, $ME;
$result = false;
$url = null;
if ($PAGE->has_set_url()) {
$url = $PAGE->url;
} else if ($ME !== null) {
$url = new moodle_url(str_ireplace('/index.php', '/', $ME));
}
if ($url !== null) {
$result = $url->compare(context_system::instance()->get_url(), URL_MATCH_BASE);
}
return $result;
}
It is a blatant example of defensive programming but with Moodle you can never be too sure.