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:If the function is
staticthen instead of$this->you would useself::most of the time:If the function is
staticthere 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.