1

我有一堂类似的课

class x {
  function __construct($file){
   $this->readData = new splFileObject($file); 
 }

 function a (){
  //do something with $this->readData;  
 }

 function b(){
   //do something with $this->readData; 
 }
}

$o = new x('example.txt');
echo $o->a(); //this works
echo $o->b(); //this does not work. 

似乎只有第一个调用的方法才有效,如果将它们一起调用,则只有调用的第一个方法才有效。我认为这个问题与我不了解new对象是如何构造的有关。

4

1 回答 1

0

该构造被加载到类的实例中。你只实例化它一次。并访问两次。是不同的动作。如果要读取文件总是取的,应该创建一个读取这个文件的方法,并在所有其他的内部触发这个方法。

我测试了你的代码,它工作正常。我相信它应该查看日志并查看是否出现任何错误。如果该文件不存在,您的代码将停止。
在您的 apache 日志中查找此错误:

PHP Fatal error: Uncaught exception 'RuntimeException' with message 'SplFileObject::__construct(example.txt): failed to open stream

回答您的评论,这可以是一种方式:

<?php
class x {

 private $defaultFile = "example.txt";

 private function readDefaultFile(){
    $file = $this->defaultFile;
    return new splFileObject($file); 
 }

 function a (){
    $content = $this->readDefaultFile();
    return $content ;
 }

 function b(){
    $content = $this->readDefaultFile();
    return $content ;
 }

}

$o = new x();
echo $o->a();
echo $o->b();

两种方法都将返回一个对象 splFile。

于 2014-01-10T00:15:45.940 回答