
Originally Posted by
Pieman
Well, I'm fairly new to OOP and thus far I'm liking it. Though, one thing has been bothering me.
Take this example:
PHP Code:
class createform {
public $index;
protected function getfile() {
if(($file = file_get_contents($this->index)) == false) {
die("Failed to open index file.");
}
}
protected function get_pie_as_title() {
$this -> getfile();
preg_match("/\<div(.*?)title\=\\\"(.*?):nocont\:\\\"(.*?)\>(.*?)\<\/div\>/is", $file, $content);
$content = preg_replace("/\<div(.*?)title\=\\\"(.*?):nocont:\\\"(.*?)\>/is", "", $content[0]);
preg_match_all("/\<(.*?)title\=\\\"pie.(.*?)\\\"(.*?)>(.*?)\<\/(.*?)\>/is", $content, $matches);
}
}
Now, $file will only exist inside the function getfile(). So how can I make it possible to use $file in other functions? (get_pie_as_title in this case)
PHP Code:
class createform {
public $index;
private $_file;
protected function getfile() {
if(($this->_file = file_get_contents($this->index)) == false) {
die("Failed to open index file.");
}
}
}
Simply the same way you stored $index, only difference is that it should be private, considering only your class needs to have access to it. In fact, you could've just returned the value of $file.
PHP Code:
class createform {
public $index;
protected function getfile() {
if(($file = file_get_contents($this->index)) == false) {
die("Failed to open index file.");
}
return $file;
}
protected function get_pie_as_title() {
$file = $this->getfile();
preg_match("/\<div(.*?)title\=\\\"(.*?):nocont\:\\\"(.*?)\>(.*?)\<\/div\>/is", $file, $content);
$content = preg_replace("/\<div(.*?)title\=\\\"(.*?):nocont:\\\"(.*?)\>/is", "", $content[0]);
preg_match_all("/\<(.*?)title\=\\\"pie.(.*?)\\\"(.*?)>(.*?)\<\/(.*?)\>/is", $content, $matches);
}
}