0

我有这个函数可以在我的 file.php 中插入代码:

function InsertData($nombre, $var1, $var2, $var3)
{
    $file = fopen("$nombre".".php", "r+");
    // Seek to the end
    fseek($file, SEEK_END, 0);
    // Get and save that position
    $filesize = ftell($file);
    // Seek to half the length of the file
    fseek($file, SEEK_SET, $filesize / 1);
    // Write your data
    fwrite($file, "<?php
class " ."$nombre". "\n
{\n
private $" ."$var1;". "\n
private $" ."$var2;". "\n
private $" ."$var3;". "\n
\n\n
    public function __construct()\n
    {\n
        $this->setData($" ."$var1". ", $" ."$var2". ", $" ."$var3". ");\n
        //parent::__construct();\n

    }
\n\n
    public function setData($" ."$var1". ", $" ."$var2". ", $" ."$var3". ")\n
    {\n
        $this->" ."$var1". "= $" ."$var1;". "\n
        $this->" ."$var2". "= $" ."$var2;". "\n
        $this->" ."$var3". "= $" ."$var3;". "\n
    }
\n\n
    public function printData()
    {\n
        echo \"SomeThing : \" . $this->" ."var1". ". \" \" . $this->" ."var2". ".     \"\n\";\n
        echo \"Other : \" . $this->" ."var3". ". \"\n\";\n
    }
\n\n
}
\n\n
?>");
    // Close the file handler
    fclose($file);
}

但是当我调用它时,我得到了这个错误: Catchable fatal error: Object of class Creator could not be convert to string in create.php on line 37

第 37 行是:

$this->" ."$var1". "= $" ."$var1;". "\n

我在其他文件中这样称呼它:

$lol = new Creator();
$lol->CreateFile($input);
$lol->InsertData($input, $input1, $input2, $input3);

我该如何解决这个问题?

4

1 回答 1

0

您为尝试生成的整个班级使用了错误的引号。尝试将双引号"改为单引号'。该错误是因为当您使用"$this"PHP 时试图调用$this->__toString(),在此上下文中$this仍然是来自外部代码的变量。使用'$this'(单引号)只不过是简单的字符串。

另一个解决方案应该是在之前添加反斜杠$this-"\$this"

于 2012-12-20T16:41:44.313 回答