【问题标题】:Displaying form information with PHP classes使用 PHP 类显示表单信息
【发布时间】:2013-11-03 01:50:20
【问题描述】:

我正在尝试显示表单中的信息。这是我的代码让我感到困惑:

<?php
//include the person class
require ('objects/classes/person.class.php');

$person = new Person();

//set person attributes
$person->first_name = $_POST["first_name"];
$person->last_name = $_POST["last_name"];
$full_name = $person->retrieve_full_name();
//display the name
echo "Your full name is " . $full_name  . ". <br />";
echo "Your first name is " . $person . ". <br />";
echo "Your last name is " . $person . ".";


?>

这是我的课程代码:

class Person {

//private attributes
private $first_name;
private $last_name;

//get function
public function __get($name){
    return $this->$name;
}
//set function
public function __set($name, $value){
    $this->$name=$value;    

}

public function retrieve_full_name(){
    return $full_name = $this->first_name . ' ' . $this->last_name;

}
}
?>

提交时我也收到此错误: 你的全名是 www dddd。 可捕获的致命错误:第 13 行的 /home/gaddough/cit21500/exercises/objects/login.php 中的 Person 类对象无法转换为字符串

我知道它在某个地方很容易解决,但我无法弄清楚任何帮助都会很棒!

【问题讨论】:

  • return $full_name = $this-&gt;first_name . ' ' . $this-&gt;last_name; 这在 imo 中毫无意义,应该等于 return $this-&gt;first_name . ' ' . $this-&gt;last_name;

标签: php forms class submit


【解决方案1】:

看起来您正在尝试将 $person 对象作为字符串打印在这些行上:

echo "Your first name is " . $person . ". <br />";
echo "Your last name is " . $person . ".";

试试这个,打印 first_name 和 last_name 实例变量:

echo "Your first name is " . $person->first_name . ". <br />";
echo "Your last name is " . $person->last_name . ".";

【讨论】:

  • 是的。这工作得很好。我知道事情就是这么简单!谢谢!
  • @user2220653 如果这个答案对你有用,请mark it as accepted
【解决方案2】:

首先要注意的是你的方法是正确的,但执行是错误的。如果您查看您的代码,您会发现您在函数(方法)中使用了局部变量,并且从不接触私有成员变量。

您的person 类需要设置 $first_name 和 $last_name,然后当您调用“get”函数时,您可以取回这些变量。

class person
{
private $first_name;
private $last_name;

public function set_name( $first, $second )
{
    if( !is_empty($first) )
    {
        $this->first_name = $first;
    }
    if( !is_empty($second) )
    {
        $this->last_name = $second;
    }
}

public function get_full_name()
{
    return $this->first_name ." ". $this->last_name;
}

}

并对其进行测试(因为我没有 - 我只是将其作为示例编写)

<?php
$person = new person();

$person->set_name( "James", "Dean" );

echo $person->get_full_name();
?>

当然,你也可以分别为名字和姓氏分别写 get :)

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 2011-09-27
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2023-04-06
    相关资源
    最近更新 更多