选择“菜单对象”


Select Menu Object

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

'班级导师 {

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;

如果我放在类外的页面上,但在类中出现错误,它可以工作:可捕获的致命错误:方法导师::__toString() 必须返回字符串值

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

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

$output = null。您需要使用 $this->output 将其设置为函数中的类变量

public function __construct($nid)
{   
$this->output .= '<select name="mentor_id">';
$this->output .= '</select>';

返回$this->输出; }

public function __toString(){   
    return $this->output;
}
<?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;
?>