How do I call a function that belongs to the same class within that class?
I have:
class BaseConfig {
public $page ;
public $htmlRoot = 'assets/html/';
public function getPageTitle(){
echo $page = $_GET['p'];
}
public function getContent(){
$file = getPageTitle().'.php';
return readfile($htmlRoot.$file);
}
}
I get the following error when I call
<?PHP Config::getContent();?>
Fatal error: Call to undefined function getPageTitle() in C:\Xit\xampp\htdocs\IMS3\assets\Config.php on line 17
I am creating my own simple framework by the way.
Thanks guys, $this does not work, it just says I can't use it out of object context.
'self' worked so thanks.
Could you please elaborate on the security hole mentioned by Radu?
@S3Mi The file being read is just html. In this use case is what I have done still bad or is it ok?
You need to use $this->
before the function name:
$file = $this->getPageTitle().'.php';
If the function is static
then instead of $this->
you would use self::
most of the time:
$value = self::someStaticFunction();
If the function is static
there is also a possible scenario where you might need to call it using late static binding, e.g. static::someStaticFunction()
. However that hints to a problematic class design so I 'm just mentioning it for completeness.
$file = $this->getPageTitle().'.php' ;
class BaseConfig {
public $page ;
public $htmlRoot = 'assets/html/';
public function getPageTitle(){
return $this->page = $_GET['p'];
}
public function getContent(){
$file = $this->getPageTitle().'.php';
return readfile($this->htmlRoot.$file);
}
}
I see that you have files in separate folder and I guess that you don't have any crucial/confidential data in there, but it doesn't solve access to other folders.
One could set $_GET['p'] to '../index.php' and get your php code. It's a big security issue.
I suggest you read about input sanitization and validation.
Never serve .php files by readfile() or any function that passes raw content. .php files should be interpreted by PHP. Exposing .php code is very bad.