0

I have an interface like this:

interface General {
    public function getFile($file);

    public function searchFile($to_search);
}

I have a class, like so:

class Parent implements General {


    public function getFile($file) {
       $loaded = file($file);
   }

    public function searchFile($to_search) {
    $contents = $this->getFile(); // doesn't work because I need the $file from get_file()!
    // searches file
    // returns found items as collection
    }
}

Then in the code, I can do something like....

$file = "example.txt";
$in = new Parent();
$in->getFile($file)
$items = $in->searchFile('text to search');
foreach($item as $item) {
    print $item->getStuff();
} 

All the examples I have seen to reference another function within a class don't take an argument.

How do I reference the $file from getFile($file) so that I can load the file and start searching away? I want to implement it through the interface, so don't bother changing the interface.

1
  • You need to pass in a value for $file. Where that value comes from is entirely up to you. Commented Jan 15, 2015 at 17:16

2 Answers 2

2

Pass the file as a constructor argument, and save its contents as a property.

class Parent implements General {
    private $file;
    public function __construct($file) {
        $this->file = file($file);
    }
    public function searchFile($to_search) {
        $contents = $this->file;
        // proceed
    }
}

Actually you don't need to do that constructor stuff, just have the getFile function save its result in $this->file. I just think it makes more sense as a constructor :p

Sign up to request clarification or add additional context in comments.

1 Comment

Totally agree with putting this in the constructor.
1

Since you're already calling getFile() from outside the class, how about loading it as a class property, so you can easily access it in the searchFile() method:

class Parent implements General {

    protected $loaded;

    public function getFile($file) {
        $this->loaded = file($file);
    }

    public function searchFile($to_search) {
        $contents = $this->loaded;
        // searches file
        // returns found items as collection
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.