开发者

PHP: Calling a user-defined function inside constructor?

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:

<?p开发者_Python百科hp
    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!


$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


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()


you can call with $this

<?php
    class userAuth {

        function userAuth($username, $password){
             $this->confirmUser($username, $password);
        }

        function confirmUser($username, $password){
                   //code
        }
    }

    $signin_user = new userAuth($username, $password);

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜