PHP: Calling a user-defined function inside constructor?
There is no difference between calling a function inside a constructor and calling from somewhere else. If the method is declared in the same class you should use $this->function()
By the way, in php5 you are suggested to name your constructor like this:function __construct()
If not then put public
keyword before your constructor definition like this public function userAuth()
$this->nameOfFunction()
But when they are in a class, they are called Methods.
Be careful with using $this in a constructor, though, because in an extension hierarchy, it can cause unexpected behaviour:
<?php
class ParentClass {
public function __construct() {
$this->action();
}
public function action() {
echo 'parent action' . PHP_EOL;
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
$this->action();
}
public function action() {
echo 'child action' . PHP_EOL;
}
}
$child = new ChildClass();
Output:
child action
child action
Whereas:
class ParentClass {
public function __construct() {
self::action();
}
public function action() {
echo 'parent action' . PHP_EOL;
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
self::action();
}
public function action() {
echo 'child action' . PHP_EOL;
}
}
$child = new ChildClass();
Output:
parent action
child action