-1

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.

Thank you in advance for the help!

index.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. 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.

Jason
  • 1,105
  • 3
  • 16
  • 30

1 Answers1

0

You forgot to return the value of $this->getUserId($username); in your constructor but that doesn't matter anyway as in PHP constructors do not return values. 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;
    }
}
John Conde
  • 217,595
  • 99
  • 455
  • 496