PHP method call reports error about it being undef

2019-03-05 11:48发布

问题:

I believe my class is correct but when I try to echo the output of the class I get an error on line 28: the line " echo 'Your full name ...." is line 28. Any help would be nice

<?php

echo 'Your full name is ' . $person->retrieve_full_name() . '.';

?>

This is where I created the function "retrieve_full_name"

public function __retrieve_full_name() {
    $fullname = $this->firstname . ' . ' . $this->lastname;
    return $fullname;
}/* This ends the Full Name Function*/

the error I get is

Fatal error: Call to undefined method stdClass::retrieve_full_name() in /home/mjcrawle/processlogin2.php on line 28

回答1:

your function is called __retrieve_full_name, but you call retrieve_full_name. notice the missing underscores.

double underscores are usually the prefix for php internal/magic functions, i would advise against using them in your function names.



回答2:

Your immediate error is due to the fact that you call your method by the wrong name. And:

  • don't use underscores to start a method name
  • don't use underscores in method names at all, if you care for best practice, use camel casing instead retrieveFullName().


回答3:

public function retrieve_full_name() {