为什么PHP认为我的方法是未定义的?

时间:2011-02-26 23:55:05

标签: php

  

可能重复:
  PHP function Question

我之前提过这个问题,但我认为我没有提供足够的代码来回答这个问题。我绞尽脑汁,我无法弄明白。这是错误

我收到错误“致命错误:在第25行的/home/mjcrawle/public_html/processlogin2.php中调用未定义的方法person :: retrieve_full_name()”

Html页面Processlogin2.php页面:

<?php
/*include the class file*/
require_once('class/person_class.php');

$person = new Person;

/*instantiate the person object*/
$person->firstname = $_POST['firstname'];
$person->lastname = $_POST['lastname'];

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Process Login</title>
</head>

<body>
<p>
<?php

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

?>

</p>
</body>
</html>

我创建的班级表单包括我的所有功能和属性等......

<?php
/*person*/

class person{
    /*construct function*/
    public function __contstruct() {
    }/* This end the Construct Functions*/

    public function __destructor() {

    }
    /*class attribute*/
    private $lastname;
    private $firstname;

    /*get function */
    public function __get($name){
    return $this-> $name;

    }/* This ends the Get Functions*/

    /*This function is going to have to parameters with it.  We are going to add the this attribute to it.*/

    public function __set($name, $value) {
        $this ->$name=$value;   
    }/* This ends the Set Functions*/

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

}

?>

2 个答案:

答案 0 :(得分:3)

您的功能名为__retrieve_full_name(),您尝试拨打retrieve_full_name()。它无法工作,你必须在课堂上重命名。

我认为你在PHP中误解了"magic" method的概念。 PHP中的所有类都已经定义了一些方法,这些方法称为魔术方法,所有方法都以__开头,以区别于您自己编写的方法。 __set(),__ get(),__ construct和__destruct()就是这样的方法。

如果我可以给你一个建议,如果你把它们留空,就没有必要声明一个构造函数或析构函数,你可以安全地从你的类中删除它们。

这是你的Personn类的新版本应该有效:

class person{
    /*class attribute*/
    private $lastname;
    private $firstname;

    /*get function */
    public function __get($name){
        return $this-> $name;
    }/* This ends the Get Functions*/

    /*This function is going to have to parameters with it.  We are going to add the this attribute to it.*/

    public function __set($name, $value) {
        $this ->$name=$value;   
    }/* This ends the Set Functions*/

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

答案 1 :(得分:0)

如果您参考here

只有特定时间才应考虑使用魔术方法。我相信你的__retrieve_full_name()不应该是这些例外之一。

  

除非您需要一些记录的魔术功能,否则建议您不要在PHP中使用带__的函数名。

希望这有帮助。

相关问题