如何确保在我尝试访问静态属性时执行构造函数?

I have a class for the user details. I want to call for example UserDetails::$email from my application, but it's empty becuase it does not execute the constructor. How should I solve this?

<?php

class UserDetails {

    public static $email;
    private $password;
    public static $role;
    public static $active;

    public function __construct() {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $this->email = $auth->getIdentity()->email;
            $this->password = $auth->getIdentity()->password;
            $this->role = $auth->getIdentity()->role;
            $this->active = $auth->getIdentity()->active;
        }
    }

}

I think you should read up on OOP basics. Your class has some major mistakes in it.

First of all, your constructor will not set $email, $role, or $active. You declared those fields as static. Static fields can only be accessed from a static context. The constructor is not a static context.

If you wanted those fields to be static -- and you don't -- you would set them from a static method like this:

public static function setEmail($email)
{
    self::$email = $email;
}

There is no reason for those fields to be static. Each $email, $role, and $active are tied to a specific user who is tied to a specific instance of your UserDetails class.

Finally, those fields should not be public. Public fields can be accessed directly from outside of the class. This means that anyone can change the value of a public field at any time from any script. You should make the fields private or protected and access them through public getter methods.

Here's an example of what a basic stub for this class might look like:

<?php

class user {

    private $firstName;
    private $lastName;
    private $email;
    private $password;
    private $role;


    public function __construct($firstName, $lastName, $email, $password, $role)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->email = $email;
        $this->password = $password;
        $this->role = $role;
    }


    public function getFirstName()
    {
        return $this->firstName;
    }


    public function getLastName()
    {
        return $this->lastName;
    }

    public function getEmail()
    {
        return $this->email;
    }


    public function getRole()
    {
        return $this->role;
    }


}

You would use the class like this:

You would use it like this:

$don_draper = new user('Donald', 'Draper, 'dondraper@gmail.com', '123xYz', 'admin');

$email = $don_draper->getEmail();

You cannot initialize a static property to another variable, to a function return value, or to an object.

I thing you should take a look at the documentation: http://php.net/manual/en/language.oop5.static.php