繁体   English   中英

PHP:在构造函数中调用用户定义的函数?

[英]PHP: Calling a user-defined function inside constructor?

我在它的构造函数中有一个类userAuth我添加了代码来检查用户是否有效,如果会话中没有值,那么我检查 cookie(作为“记住我”功能的一部分),如果里面有一些值cookies 然后我调用一个函数ConfirmUser从数据库中检查它的真实性。 根据confirmUser 函数返回的值,我在构造函数中返回一个bool(true 或fales)值。

我已经创建了我的班级:

<?php
    class userAuth {

        function userAuth(){
            //code
        }

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

    $signin_user = new userAuth();

?>

confirmUser函数接受两个字符串类型的参数,并返回一个整数值 0、1、2。

我无法在构造函数中添加confirmUser函数的代码,因为我在应用程序的更多地方使用了这个函数。

所以,我想知道如何在 PHP 的构造函数中调用用户定义的函数。 请帮忙。

谢谢!

$this->nameOfFunction()

但是当它们在一个类中时,它们被称为方法。

但是,在构造函数中使用 $this 时要小心,因为在扩展层次结构中,它可能会导致意外行为:

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

输出:

child action
child action

然而:

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

输出:

parent action
child action

在构造函数内部调用函数和从其他地方调用没有区别。 如果该方法在同一个类中声明,则应使用$this->function()

顺便说一句,在 php5 中,建议您像这样命名构造函数:
function __construct()

如果没有,则将public关键字放在您的构造函数定义之前,例如public function userAuth()

你可以用 $this 打电话

<?php
    class userAuth {

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

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

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

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM