2015-10-17 34 views
0

我正在学习PHP面向对象编程,并尝试读取和写入文件中的数据。不过,这并不创造的所有文件,并给了我一个错误信息:OOP类不能写入文件,因为is_writable返回false

Change your chmod to test.txt

这里是我的代码:

<?php 
class log 
{ 
    public function Write($strFileName, $strData) 
    { 
     if (!is_writable($strFileName)) 
     die("Change your chmod to ".$strFileName); 

     $handle = fopen($strFileName,'a+'); 
     fwrite($handle,"\r".$strData); 
     fclose($handle); 
    } 
    public function Read($strFileName) 
    { 
     $handle = fopen($strFileName,'r'); 
     return file_get_contents($strFileName); 
    } 
} 
$log = new log(); 
$log->Write('test.txt','Hello World!'); 
?> 
+0

你能提供错误信息吗? –

+0

将您的chmod更改为test.txt – Pouya

回答

1

我会用file_put_contentsFILE_APPEND | LOCK_EX标志,简化你的代码,并确保文件被正确锁定和解锁。

此外,您不需要打开文件的句柄,因为file_get_contents自己处理打开和关闭。

<?php 
class log 
{ 
    public $logFilePath; 
    public function __construct($logFilePath) { 
     $this->logFilePath = $logFilePath; 
    } 
    public function Write($strData) 
    { 
     file_put_contents($this->logFilePath, $strData, FILE_APPEND | LOCK_EX); 
    } 
    public function Read() 
    { 
     return file_get_contents($this->logFilePath); 
    } 
} 
$log = new log('test.txt'); 
$log->Write('Hello World!'); 
echo $log->Read(); 
?> 

<?php 
class log 
{ 
    public function Write($strFileName, $strData) 
    { 
     file_put_contents($strFileName, $strData, FILE_APPEND | LOCK_EX); 
    } 
    public function Read($strFileName) 
    { 
     return file_get_contents($strFileName); 
    } 
} 
$log = new log(); 
$log->Write('test.txt','Hello World!'); 
?> 

虽然我们正在学习OOD,文件名应包含在类中,因为它是恒定的,以创建日志对象,当使用对象和读/写它节省了杂波

+0

仍然会出现错误:将您的chmod更改为test.txt – Pouya

+0

您没有使用我的代码,因为该错误不在其中,因为您正在尝试测试一个文件是否存在不存在是可写的,如果该文件不存在,则它不能被写入,并且您将始终得到该错误。 – Wobbles

+0

如果上述功能适用于您,请将其标记为已接受并投票。 – Wobbles

相关问题