简体   繁体   English

PHP从构造函数调用的函数中获取值

[英]PHP get value from function called by constructor

I have a feeling I'm overlooking something simple but I can't figure out how to get a value from a function that is called by the constructor within my class.我有一种感觉,我忽略了一些简单的事情,但我无法弄清楚如何从我的类中的构造函数调用的函数中获取值。 The below is a very simple example but, essentially, I need to use the userId value on my index.php page which is returned by the function getUser which is called by the constructor.下面是一个非常简单的示例,但本质上,我需要在 index.php 页面上使用 userId 值,该值由构造函数调用的 getUser 函数返回。

Thank you in advance for the help!预先感谢您的帮助!

index.php:索引.php:

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

class/function:类/功能:

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;
        }
}

I should add that I know I can initialize the class then call the function from index.php and get the value that way.我应该补充一点,我知道我可以初始化类,然后从 index.php 调用函数并以这种方式获取值。 This is very simple example but some of the scripts I'm working on call 6 or 7 functions from within the constructor to perform various tasks.这是一个非常简单的示例,但我正在处理的一些脚本从构造函数中调用 6 或 7 个函数来执行各种任务。

You forgot to return the value of $this->getUserId($username);你忘了返回$this->getUserId($username); in your constructor but that doesn't matter anyway as in PHP constructors do not return values.在您的构造函数中,但这无关紧要,因为在 PHP 构造函数中不返回值。 You will have to make a second call to get that value after you initiate your object.在启动对象后,您将不得不进行第二次调用以获取该值。

$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;
    }
}

Or perhaps more intelligant:或者也许更智能:

$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;
    }
}

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

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