简体   繁体   English

如何使用PHP类中设置的变量?

[英]How can I use variables set in a PHP class?

In this little example below in PHP what would be a good way to be able to create the variables in the user class and then be able to use them on any page where I create a user object? 在下面的PHP这个小示例中,怎样才能在用户类中创建变量,然后在我创建用户对象的任何页面上使用它们,是一个好方法?

<?PHP
//user.class.php file
class User
{

    function __construct()
    {
        global $session;
        if($session->get('auto_id') != ''){
            //set user vars on every page load
            $MY_userid = $session->get('auto_id'); //user id number
            $MY_name = $session->get('disp_name');
            $MY_pic_url = $session->get('pic_url');
            $MY_gender = $session->get('gender');
            $MY_user_role = $session->get('user_role');
            $MY_lat = $session->get('lat');
            $MY_long = $session->get('long');
            $MY_firstvisit = $session->get('newregister');
        }else{
            return false;
        }
    }
}
?>



<?PHP
// index.php file
require_once $_SERVER['DOCUMENT_ROOT'].'/classes/user.class.php';

$user = new User();

//how should I go about making the variables set in the user class available on any page where I initiate the user class?
// I know I can't use 
// echo $MY_pic_url;
// 1 way I can think of is to have the class return an array but is there another way?

?>

Make them public members: 使其成为公共成员:

class user
{
  public $first_name;

function __construct()
{
$this->first_name = $_SESSION['first_name'];
}


}

$user = new user();

echo $user->first_name;

To elaborate on Lance' answer; 详细阐述兰斯的答案; if the point of the class is to be nothing more than an container for the data, in stead of doing something with the data you're pretty safe. 如果该类的重点只是作为数据的容器,而不是对数据做些事情,那么您就很安全了。 But a good principal of OOP is to stick to encapsulation . 但是OOP的一个很好的原则是坚持封装 Encapsulation means, amongst other things, that you hide the inner details of your object from the outside and only let the outside access the fields through it's interface methods. 封装意味着,除其他外,您从外部隐藏对象的内部细节,并且仅允许外部通过其接口方法访问字段。

Let's say you don't want the fields in the User object to be altered from the outside, but only accessed, then you'ld be better of with something like the following: 假设您不希望从外部更改User对象中的字段,而只希望对其进行访问,那么最好使用以下内容:

class User
{

    private $_userId;
    // and a bunch of other fields

    public function __construct( $data )
    {
        // do something with the data
    }

    public function getUserId()
    {
        return $this->_userId;
    }
    // and a bunch of other getters to access the data

}

In all honesty, you could use magic methods like __set and __get to simulate what you want and catch any unwanted altering in the __set method. 老实说,您可以使用诸如__set和__get之类的魔术方法来模拟所需内容,并捕获__set方法中不需要的更改。

Furthermore, I wouldn't use the session as a global variable. 此外,我不会将会话用作全局变量。 You should pass the session object as an argument to it's constructor (like I illustrated in the example). 您应该将会话对象作为其构造函数的参数传递(如我在示例中所示)。 This enforces loose coupling. 这将导致松散耦合。 Because now your User objects are tied to the global session object, but with passing it to the constructor any data could be passed in. This makes the class more flexible. 因为现在您的User对象已绑定到全局会话对象,但是将其传递给构造函数后,任何数据都可以传入。这使类更加灵活。

Edit: 编辑:
Here's an example of how you could pass an object (for instance your session object) to the constructor. 这是一个如何将对象(例如会话对象)传递给构造函数的示例。 One thing to keep in mind is that, the way your session object is designed, it still, somewhat, enforces tight coupling, because it mandates getting properties through the get() method. 要记住的一件事是,会话对象的设计方式在某种程度上仍会强制紧密耦合,因为它要求通过get()方法获取属性。

class User
{
    public function __construct( $data )
    {
        $this->_id = $data->get( 'id' );
        $this->_firstname = $data->get( 'firstname' );
        // etc
    }
}

// usage
$session = new YourSessionObject();
$user = new User( $session );

You have a few options at hand to propagate loose coupling, and making you User object a little more flexible. 您手边有一些选择可以传播松散的耦合,并使您的User对象更加灵活。

Mandate that the data for you User object is provided as: 要求为您的User对象提供以下数据:

distinct arguments 独特的论点

class User
{
    protected $_id;
    protected $_firstname;
    // etc;

    public function __construct( $id, $firstname, /* etc */ )
    {
        $this->_id = $id;
        $this->_firstname = $firstname;
        // etc
    }
}

// usage
$session = new YourSessionObject();
$user = new User( $session->get( 'id' ), $session->get( 'firstname' ), /* etc */ );

array 数组

class User
{
    protected $_fields = array(
        'id' => null,
        'firstname' => null,
        // etc
    );

    // dictate (type hint) that the argument should be an array
    public function __construct( array $data )
    {
        foreach( $data as $field => $value )
        {
            if( array_key_exists( $field, $this->_fields )
            {
                $this->_fields[ $field ] = $value;
            }
        }
    }
}

// usage
$session = new YourSessionObject();
$array = /* fill this array with your session data */; 
$user = new User( $array );

implementing some interface 实现一些接口

// objects that implement this interface need to implement the toArray() method
interface Arrayable
{
    public function toArray();
}

class User
{
    protected $_fields = array(
        'id' => null,
        'firstname' => null,
        // etc
    );

    // dictate (type hint) that the argument should implement Arrayable interface
    public function __construct( Arrayable $data )
    {
        // get the data by calling the toArray() method of the $data object
        $data = $data->toArray();
        foreach( $data as $field => $value )
        {
            if( array_key_exists( $field, $this->_fields )
            {
                $this->_fields[ $field ] = $value;
            }
        }
    }
}

class YourSessionObject implements Arrayable
{
    public function toArray()
    {
        /* this method should return an array of it's data */
    }
}

// usage
$session = new YourSessionObject();
$user = new User( $session );

etc 等等

There are a few other options, but this should give you some ideas. 还有其他一些选择,但这应该可以给您一些想法。 Hope this helps. 希望这可以帮助。

Sidenote: the constructor has no return value, ie return false does not have the effect you probably intended. 旁注:构造函数没有返回值,即return false可能不会达到您预期的效果。

Either use public properties or protected properties+accessor methods. 使用公共属性或受保护的属性+访问器方法。
Or store the $session in your object and then "delegate" each query for a property to that $session object. 或将$ session存储在对象中,然后将对属性的每个查询“委派”给该$ session对象。

class User
{
  protected $session;

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

  function get($name) {
    if( ''==$this->session->get('auto_id')) {
      throw new Exception('...');
    }
    return $this->session->get($name);
  }
}
$user = new User($session);
echo $user->get('disp_name');

Or use the "magic" __get() method, eg 或使用“魔术” __get()方法,例如

class User
{
  protected static $names = array(
    'auto_id', 'disp_name', 'pic_url', 'gender',
    'user_role', 'lat', 'long', 'newregister'
  );
  protected $properties = array();
  function __construct()
  {
    global $session;
    if($session->get('auto_id') != '') {
      foreach(self::$names as $n) {
        $this->properties[$n] = $session->get($n);
      }
    }
    else {
      throw new Exception('...');
    }
  }

  function __get($name) {
    return isset($this->properties[$name]) ? $this->properties[$name] : null;
  }
}


$user = new User;
echo $user->disp_name;

Use attributes to store it. 使用属性来存储它。

<?PHP
//user.class.php file
class User
{

    public $MY_userid;
    public $MY_name;
    public $MY_pic_url;
    public $MY_gender;
    public $MY_user_role;
    public $MY_lat;
    public $MY_long;
    public $MY_firstvisit;

    function __construct()
    {
        global $session;
        if($session->get('auto_id') != ''){
                //set user vars on every page load
                $this->MY_userid = $session->get('auto_id'); //user id number
                $this->MY_name = $session->get('disp_name');
                $this->MY_pic_url = $session->get('pic_url');
                $this->MY_gender = $session->get('gender');
                $this->MY_user_role = $session->get('user_role');
                $this->MY_lat = $session->get('lat');
                $this->MY_long = $session->get('long');
                $this->MY_firstvisit = $session->get('newregister');
        }else{
                return false;
        }
    }
}
?>

最初创建用户对象后,也可以将其保存在$ _SESSION变量中。

<?PHP
//user.class.php file
class User
{

    function __construct()
    {
        var $MY_userid;
        var $MY_name;
        var $MY_pic_url;
        var $MY_gender;
        var $MY_user_role;
        var $MY_lat;
        var $MY_long;
        var $MY_firstvisit;

        global $session;
        if($session->get('auto_id') != ''){
                //set user vars on every page load
                $this->MY_userid = $session->get('auto_id'); //user id number
                $this->MY_name = $session->get('disp_name');
                $this->MY_pic_url = $session->get('pic_url');
                $this->MY_gender = $session->get('gender');
                $this->MY_user_role = $session->get('user_role');
                $this->MY_lat = $session->get('lat');
                $this->MY_long = $session->get('long');
                $this->MY_firstvisit = $session->get('newregister');
        }else{
                return false;
        }
    }
}
?>



<?PHP
// index.php file
require_once $_SERVER['DOCUMENT_ROOT'].'/classes/user.class.php';

$user = new User();
print $user->MY_name;
?>

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

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