选择菜单对象

时间:2015-01-24 23:57:39

标签: php oop tostring

我正在尝试创建一个可以重复使用的选择菜单对象:

`班导师{

var $nid;
var $level_id;
var $output;

public function __construct($nid)
{   
include 'con.php'; 
$stmt = $conn->prepare(
'SELECT a.uid, pp.fName, pp.lName FROM primary_profile as pp LEFT JOIN attributes as a ON pp.uid = a.uid WHERE nid = :nid AND :level_id = level_id');
$stmt->execute(array(':nid' => $nid, ':level_id' => 3));

$output .= '<select name="mentor_id">';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output .='<option value="'.$row['uid'].'">'.$row['fName']. ' ' .$row['lName'].'</option>';
}
$output .= '</select>';

return $output;
}

public function __toString(){   
    return $output;
}

}`

在我的页面上,我打电话:

$mentor_select = new Mentor($nid); echo $mentor_select;

如果我放在课外的页面但是在课堂上我收到错误它是有效的: 可捕获的致命错误:方法Mentor :: __ toString()必须返回字符串值

我知道这意味着__toString必须输出一个字符串,但据我所知,$ output是一个字符串......

我是OOP的新手。请帮我解决我所缺少的问题

2 个答案:

答案 0 :(得分:0)

$ output = null。您需要使用$ this-&gt; output

将其设置为函数内的类变量
public function __construct($nid)
{   
$this->output .= '<select name="mentor_id">';
$this->output .= '</select>';

//返回$ this-&gt;输出;    }

public function __toString(){   
    return $this->output;
}

答案 1 :(得分:0)

<?php

class Mentor {

    //Members declared as private may only be accessed by the class that defines the member
    //Also you can declare members of a class as protected, and public. Read about that.
    private $nid;
    private $level_id;
    private $output;

    public function __construct($nid)
    {
        $this->level_id = 0;//You can initialize properties to their default values here
        $this->nid = $nid;
        $this->output = "output value $this->nid";

        //return $this->output; constructors should not return values explicitly
        //they are used to instantiate the class
    }

    public function __toString(){   
        return $this->output;
    }

    public function getOutput(){
        return $this->output;//property output is private, so we define a public method which allows us to read it's value outside this class.
    }
}

    $mentor = new Mentor(3);// you don't need to return value from your constructor, because you have defined __toString magic method.
    echo $mentor;

?>