AAA
AAA

Reputation: 2032

PHP functions within class -- call function within class

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.

Upvotes: 0

Views: 56

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

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

Upvotes: 2

mopo922
mopo922

Reputation: 6381

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
    }
}

Upvotes: 1

Related Questions