我的文件创建者类中存在小问题。 我对OOP有点新意,所以我觉得我犯了错 这是班级
<?php
class Files{
public $filename ;
public $content ;
function Files($filename)
{
$this->filename = $filename;
}
function createfile()
{
$file = fopen($this->filename, "w+") or die('cant create file ');
return $file ;
}
function writetofile($content)
{
fwrite($this->createfile,$content) ;
}
function closecon()
{
fclose($this->createfile);
}
}
?>
以下是我如何使用它
<?php
include 'classes/class.files.php';
$create = new files('tmp/index.html');
$content = '<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>';
$create->createfile() ;
$create->writetofile($content) ;
$create->closecon() ;
?>
当我调用test.php文件时,它会给我这个错误
Warning: fwrite(): supplied argument is not a valid stream resource in C:\AppServ\www\cms\classes\class.files.php on line 16
Warning: fclose(): supplied argument is not a valid stream resource in C:\AppServ\www\cms\classes\class.files.php on line 20
答案 0 :(得分:2)
您需要将文件指针资源存储在属性中(而不是每次都调用createfile
)。此外,您甚至没有调用createfile
,而是引用一个不存在的属性(您应该收到通知)。尝试这样的事情:
class Files{
public $fp;
public $filename ;
public $content ;
function Files($filename)
{
$this->filename = $filename;
}
function createfile()
{
$this->fp = fopen($this->filename, "w+") or die('cant create file ');
}
function writetofile($content)
{
fwrite($this->fp, $content) ;
}
function closecon()
{
fclose($this->fp);
}
}
此外,您的代码不是非常适合PHP5的。您的构造函数应该调用__construct
(而不是Files
),并且您的方法应该具有明确的可见性。我还建议您在实现课程时使用确切的案例:
class Files{
public $fp;
public $filename ;
public $content ;
public function __construct($filename)
{
$this->filename = $filename;
}
public function createfile()
{
$this->fp = fopen($this->filename, "w+") or die('cant create file ');
}
public function writetofile($content)
{
fwrite($this->fp, $content) ;
}
public function closecon()
{
fclose($this->fp);
}
}
$create = new Files('tmp/index.html');
答案 1 :(得分:1)
您应该有一个名为$file
的私人成员。
createfile
不应该返回文件句柄;相反,它应该将$this->file
设置为有效的文件句柄。
writetofile
应如下所示:
function writetofile($content)
{
$file != NULL || die ('didn\'t create file yet');
fwrite($this->file, $content);
}
最后,closecon
应关闭$this->file
指向的文件。请享用! :)
答案 2 :(得分:1)
首先,这是一个有效的代码片段:
class Files{
protected $filename ;
protected $content ;
protected $fd;
public function __construct($filename)
{
$this->filename = $filename;
}
public function createFile()
{
$this->fd = fopen($this->filename, "w+");
if ($this->fd === false) {
throw new Exception('Something bad happened');
}
}
public function writeToFile($content)
{
$length = strlen($content);
if ($length != fwrite($this->fd, $content)) {
throw new Exception('Something bad happened');
}
}
public function close()
{
fclose($this->fd);
}
}
$create = new Files('index.html');
$create->createFile() ;
$create->writeToFile('blah') ;
$create->close() ;
现在,改变: