phpoopsplfileobject

creating multiple instances of splFileObject


I have a class similar to this

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. 

it seems if which ever method called first only works, if they are called together only the first method that is called will work. I think the problem is tied to my lack of understand how the new object gets constructed.


Solution

  • The construct is loaded into the instance of the class. And you're instantiating it only once. And accessing twice. Are different actions. If you want to read the file is always taken, should create a method that reads this file, and within all other trigger this method.

    I tested your code and it worked normal. I believe it should look at the logs and see if any error appears. If the file does not exist your code will stop.
    Find for this error in your apache logs:

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

    Answering your comment, this can be a way:

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

    Both methods will return an object splFile.