I have a class userAuth
inside its constructor I have added code to check the user is valid or not, if there is no value in session then I check cookies (as a part of "Remember Me" feature), if there is some value inside cookies then I call a function ConfirmUser
to check its authenticity from database. On the basis of value returned by the confirmUser function I am returning a bool (true or fales) value in constructor.
I have created my class as:
<?php
class userAuth {
function userAuth(){
//code
}
function confirmUser($username, $password){
//code
}
}
$signin_user = new userAuth();
?>
confirmUser
function take two string type parameters and return return a integer value of 0, 1, 2.
I can't add code of confirmUser
function inside the constructor as I am using this function at some more places in my application.
So, I want to know how to call a user-defined function inside constructor in PHP. Please help.
Thanks!
A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.
Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.
There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With