如何着色文字

时间:2014-06-15 12:25:00

标签: php html colors echo

我有这个代码,可悲的是我无法改变任何内容或在课堂外添加STUDENT。我只能在STUDENT内进行修改,而我无法修改私有字段。但是,我需要以红色颜色显示字段$nume的值。想法?

class STUDENT {
    private $nume,$prenume;
    // Constructor 
    public function __construct($nume , $prenume){ 
        $this->nume=$nume;
        $this->prenume=$prenume;            
    }

    public function __toString(){
        return $this->nume.".".$this->prenume;

    }


}

$student = new STUDENT("mr","Jack");  
echo "student: ". $student ."<hr/>"; 

2 个答案:

答案 0 :(得分:2)

您可以将属性设为公开,以便您可以从外部访问它们:

class STUDENT 
{
    public $nume;
    public $prenume;

    // Constructor 
    public function __construct($nume , $prenume)
    { 
        $this->nume=$nume;
        $this->prenume=$prenume;            
    }

    public function __toString()
    {
        return $this->nume.".".$this->prenume;
    }
}

$student = new STUDENT("mr","Jack");  
echo "<span style='color:red'>student: ". $student->nume ."</span><hr/>"; 

或者如果您需要保持私有,您可以在类中创建一个函数来输出它:

class STUDENT 
{
    private $nume;
    private $prenume;

    // Constructor 
    public function __construct($nume , $prenume)
    { 
        $this->nume=$nume;
        $this->prenume=$prenume;            
    }

    public function __toString()
    {
        return $this->nume.".".$this->prenume;
    }

    public function displayNume()
    {
        echo "<span style='color:red'>student: ". $this->nume ."</span><hr/>"; 
    }
}

然后你可以这样访问:

$student = new STUDENT("mr","Jack");  
$student->displayNume();

答案 1 :(得分:1)

你试过......

public function __toString(){
    $red = '<span style="color: red;">' . $this->nume . '</span>';
    return $red.".".$this->prenume;

}