可捕获的致命错误:Forma类的对象无法在第35行转换为中的字符串


Catchable fatal error: Object of class Forma could not be converted to string in on line 35

我是php currenlty learnig的新手,我正在尝试学习对象,但我对这段代码有问题。它说问题出在我的postavi_html函数上。我会认真考虑任何建议,提前感谢

class Forma
{
    private $method;
    private $action;
    private $pun_html;
    function __construct ($metoda,$akcija)
    {
        $this->method = $metoda;
        $this->action=$akcija;
    }
    function gen_inputs($n)
    {
        $s="";
        for($i=0;$i<$n;$i++)
        {
            $s .="<input type='textfield' name='text$i' placeholder='text$i'/><br>";
        }
        $s .="<input type='submit' name='submit' value='Posalji'/><br>";
        return $s;
    }
    function gen_links ($href,$text,$color)
    {
        $s="<a style='color:$color;' href='$href'>$text</a>";
        return $s;
    }
    function postavi_html($broj_inputa,$href_linka,$text_linka,$boja_linka)
    {
        $this->pun_html = "<form method='$this->method' action ='$this->action'>$this-> gen_inputs($broj_inputa) . $this->gen_links($href_linka,$text_linka,$boja_linka)</form>";
    }
}
$forma= new Forma ("GET","nesto.php");
echo $forma-> postavi_html (4,"GOOGLE","www.google.com","#564898");

如果您想在字符串中包含复杂字段,可以执行以下操作:

$string = "normal and now {$a->getSomething()}"

为了更好地了解发生了什么,请在类中添加以下函数:

function __toString() { return 'myObject'; }

php正在尝试将$this转换为字符串。这就是该功能的样子:

function postavi_html($broj_inputa,$href_linka,$text_linka,$boja_linka)
{
    $this->pun_html = "<form method='{$this->method}' action ='{$this->action}'>{$this->gen_inputs($broj_inputa)} . {$this->gen_links($href_linka,$text_linka,$boja_linka)}</form>";
}

似乎问题出在postavi_html函数中使用$this->方法、$this->action。尝试以下代码

function postavi_html($broj_inputa,$href_linka,$text_linka,$boja_linka)
{
    $this->pun_html = "<form method='".$this->method."' action ='".$this->action."'>".$this->gen_inputs($broj_inputa) . $this->gen_links($href_linka,$text_linka,$boja_linka)."</form>";
   // If you want to return the form.
   return $this->pun_html;
}

注意变化'$this->method'to'".$this->method."'

输出:

<form method="GET" action="nesto.php">
    // inputs
</form>