Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 创建splFileObject的多个实例_Php_Oop_Splfileobject - Fatal编程技术网

Php 创建splFileObject的多个实例

Php 创建splFileObject的多个实例,php,oop,splfileobject,Php,Oop,Splfileobject,我有一个类似的班级 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('exa

我有一个类似的班级

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. 

似乎哪一个方法被称为first only有效,如果它们被一起调用,那么只有被调用的第一个方法有效。我认为这个问题与我不了解
新的
对象是如何构造的有关

构造被加载到类的实例中。您只实例化了一次。访问两次。这是不同的行动。如果要读取文件,则应创建一个读取此文件的方法,并在所有其他方法中触发此方法

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

PHP致命错误:未捕获异常“RuntimeException”,消息为“SplFileObject::\uu构造(example.txt):无法打开流

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

<?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();

这些不是单独的实例,您只调用了一个
x
实例
$o
。。。至于为什么第二种方法不起作用,在不知道这些方法的作用以及实际上什么“不起作用”的情况下,不可能说出来means@MarkBaker我在函数中读取一个txt文件并返回数据。因此,它不起作用意味着,如果我同时调用这两个函数,它不会返回预期的数据。这根本不能告诉我太多。。。。但是我怀疑第二个方法在第一个方法将文件读取到其结尾后,没有将文件指针倒回到文件的开头。我想你可能是对的。我认为,
new
关键字会在每次函数从构造函数调用属性时创建类的新实例。你能给我举个例子说明如何读取文件并使其他人可以访问它吗?我能做到,但我想看看是否有更好的方法来做到这一点。更新我的答案。只是个主意,谢谢。我去看看。