【问题标题】:PHP get value from function called by constructorPHP从构造函数调用的函数中获取值
【发布时间】:2015-06-18 19:28:10
【问题描述】:

我有一种感觉,我忽略了一些简单的事情,但我不知道如何从我的类中的构造函数调用的函数中获取值。下面是一个非常简单的示例,但本质上,我需要在 index.php 页面上使用 userId 值,该值由构造函数调用的函数 getUser 返回。

提前感谢您的帮助!

index.php:

$test = new Test($username);
//Need to get value of userId here....

类/功能:

class Test
{
    //CONSTRUCTOR
    public function __construct($username)
        {
            $this->getUserId($username);
        }

    //GET USER ID   
    public function getUserId($username)
        {
            //DB query here to get id
            return $userId;
        }
}

我应该补充一点,我知道我可以初始化类,然后从 index.php 调用函数并以这种方式获取值。这是一个非常简单的示例,但我正在处理的一些脚本从构造函数中调用 6 或 7 个函数来执行各种任务。

【问题讨论】:

标签: php class constructor


【解决方案1】:

您忘记在构造函数中返回 $this->getUserId($username); 的值,但这并不重要,因为 PHP 构造函数不返回值。启动对象后,您必须进行第二次调用才能获取该值。

$test = new Test();
$userId = $test->getUserId($username);

class Test
{
    // constructor no longer needed in this example

    //GET USER ID   
    public function getUserId($username)
    {
        //DB query here to get id
            return $userId;
    }
}

或许更聪明:

$test = new Test($username);
$userId = $test->getUserId();

class Test
{
    protected $username;

    public function __construct($username) 
    {
        $this->username = $username;
    }

    //GET USER ID   
    public function getUserId()
    {
        // username is now access via $this->username

        //DB query here to get id
            return $userId;
    }
}

【讨论】:

  • 知道了 - 谢谢!我想了很多,但只是想避免第二次通话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2011-03-06
  • 1970-01-01
  • 2011-03-24
  • 2010-10-05
  • 1970-01-01
相关资源
最近更新 更多