Select 菜单对象

Select Menu Object

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

`class 导师 {

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;

如果我将页面放在 class 之外但在 class 中,我会收到错误消息: 可捕获的致命错误:方法 Mentor::__toString() 必须 return 一个字符串值

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

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

$output = 空。您需要使用 $this->output

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

//return $this->output; }

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;

?>