1

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.

user2679413
  • 49
  • 1
  • 7
  • These aren't separate instances, you only have one instance of `x` that you're calling `$o`... as to why the second method doesn't work, it's not possible to say without knowing what the methods do, and what "doesn't work" actually means – Mark Baker Jan 10 '14 at 00:07
  • @MarkBaker I am reading a txt file in both function and returning the data. So, it does not work means, it does not return the intended data if I am calling the both at the same time. – user2679413 Jan 10 '14 at 00:11
  • That doesn't really tell me much at all.... but I'd suspect that the second method doesn't rewind the file pointer to the beginning of the file after the first method has read through the file to its end – Mark Baker Jan 10 '14 at 00:15

1 Answers1

0

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.

Rafael Soufraz
  • 974
  • 3
  • 11
  • 28
  • I think you may be right. I thought, the `new` keyword creates a new instances of class everytime a function calls a property from the constructor. can you give me an example on how to read the file and make it accessible by others? I can do it, but I want to see if there is a better approach to do this. – user2679413 Jan 10 '14 at 00:34
  • Update my answer. Just an idea. – Rafael Soufraz Jan 10 '14 at 00:50