我正在尝试显示表单中的信息。这是我的代码搞砸了我:
<?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中转换为字符串
我知道它在某个地方很容易修复,但我无法弄明白任何帮助都会很棒!
答案 0 :(得分:0)
看起来您正试图在这些行上将$ 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 . ".";
答案 1 :(得分:0)
首先要注意的是你的方法是正确的,但执行是错误的。如果查看代码,您将看到在函数(方法)中使用局部变量,从不触及私有成员变量。
您的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's:)
祝你好运!