【问题标题】:PHP: Calling a user-defined function inside constructor?PHP:在构造函数中调用用户定义的函数?
【发布时间】:2011-05-19 03:34:20
【问题描述】:

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

我将我的班级创建为:

<?php
    class userAuth {

        function userAuth(){
            //code
        }

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

    $signin_user = new userAuth();

?>

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

我无法在构造函数中添加 confirmUser 函数的代码,因为我在我的应用程序中的更多位置使用此函数。

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

谢谢!

【问题讨论】:

  • 放一些有问题的代码。在哪里调用函数没有区别。
  • 确保confirmUser的函数声明包含/需要,你可以在构造函数中调用confirmUser...这是什么问题?
  • 你说你在构造函数中返回一个布尔值,这有点奇怪。构造函数只能返回其类的实例。你能详细说明一下吗?

标签: php function methods constructor


【解决方案1】:

$this->nameOfFunction()

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

【讨论】:

  • 我怀疑你认为在构造函数完成之前,没有'$this'可以调用方法;但是还有。在 PHP 中,新对象存在,并且 '$this' 指向它,只要它进入构造函数。
【解决方案2】:

不过,在构造函数中使用 $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

【讨论】:

  • 感谢您解释thisself:: 之间非常重要的区别
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:

    你可以用 $this 调用

    <?php
        class userAuth {
    
            function userAuth($username, $password){
                 $this->confirmUser($username, $password);
            }
    
            function confirmUser($username, $password){
                       //code
            }
        }
    
        $signin_user = new userAuth($username, $password);
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 1970-01-01
      • 2010-12-15
      • 2017-03-12
      • 2021-11-23
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多