pass variable as an array - php

Hi in my user class i am passing the variables in constructor instead of passing variables i want to pass as an array.
Class User{
var $userid;
var $alias;
var $firstname;
var $password;
var $email;
var $photo;
var $avatar_url;
var $thumb;
var $crop_url;
var $crop_position;
protected $db;
function User($userid='',$alias='',$firstname='',$lastname='',$password='',$email='',$photo='',$avatar_url='',$thumb='',$crop_url='',$crop_position='',PDO $db){
$this->userid=$userid;
$this->alias= $alias;
$this->firstname=$firstname;
$this->lastname=$lastname;
$this->password= $password;
$this->email=$email;
$this->photo= $photo;
$this->avatar_url= $avatar_url;
$this->thumb= $thumb;
$this->crop_url= $crop_url;
$this->crop_position= $crop_position;
$this->db = $db;
}
}
and the variable coming in constructor
$user=new User($id,$alias,$firstname,$lastname,$password,$email,$photo='',$avatar_url='',$thumb='',$crop_url='',$crop_position='',$db);
this all are coming through the request variable.
Please help.Thanks

You didn't clarify what your issue is. If you want to pass an array, then pass an array. If you cannot change your API for the ctor for BC reasons, you can add another method to your User class, e.g.
class User
{
// other code …
public function populateFromArray(array $data)
{
foreach ($data as $property => $value) {
if (property_exists($this, $property)) {
$user->$property = $value;
}
}
}
}
Then you can do
$user = new User('','','','','','','','','','','',$db);
$user->populateFromArray(array(
'id' => 'johndoe',
'email' => 'jdoe#example.com',
// other …
));
The ctor call looks pretty ugly, so if you can afford to change the API, I suggest to move required arguments to the beginning of the signature. This is suggested good practise in the PHP Manual anyway, e.g. change your ctor to
public function __construct(PDO $pdo, $id = '', $email = '', …) {
Note that I changed it to the new PHP5 style constructor. Naming the ctor after the class name is PHP4 style and is not compatible with namespaces as of PHP5.3.3.. You might also want to change your var keyword to public (or better yet protected and add proper getter and setter).
Since everything but the PDO instance is optional, you can just as well remove all the optional arguments and always use your new populateFromArray method instead, reducing the instantiation to
$user = new User($db);
$user->populateFromArray($dataArray);
If you want to implement the populateFromArray functionality in other classes as well, you might want to consider adding an interface IPopulate, e.g.
interface IPopulate
{
public function populateFromArray(array $data);
}
But your classes implementing this interface would have to add the method body each time, which is a bit redundant given that our populating code is quite generic. With php.next there will be traits for an elegant solution for horizontal reuse like this.
Yet another possible solution would be to just use the Reflection API to pass the array to your regular ctor (though you should give it a benchmark afterwards because the Reflection API is considered slow). See
Pass arguments from array in php to constructor

User.php Class:
// define your default values here. so that you will not have to pass them
// everytime when you pass the array to `AssignVal` function.
Class User{
var $userid = '';
var $alias = '';
var $firstname = '';
var $password = '';
var $email = '';
var $photo = '';
var $avatar_url = '';
var $thumb = '';
var $crop_url = '';
var $crop_position = '';
protected $db;
function User(PDO $db) {
$this->db = $db;
}
}
Index.php (where you want the object to be created):
$user = assignVal('User',$arr);
functions.php (a place where you include all your functions):
// the following function creates an object with the array you send it.
// this is specially useful if your class contains a lot of variables
// thus minimizing the manual work of defining constructors again and again...
function assignVal($obj,$arr,$child=null) {
if (is_string($obj)) $obj = new $obj();
$applyon = $child == null ? $obj : $obj->$child;
if(!empty($arr)) {
foreach ($arr as $name => $val) {
$applyon->$name = $val;
}
}
if ($child != null) $obj->$child = $applyon;
else $obj = $applyon;
return $obj;
}

First create your array:
$Usr_info = array('id' => 0, 'alias' => 'value'); //add all the values you want like that
And then in your constructor you can access each item in the array:
function User($Usr_info)
{
$this->userid = $Usr_info['id'];
//and so on...
}

version for PHP5
class User {
private $userid;
...
public function assign ($class_member, $value) {
$this->$class_member = $value;
}
public function __construct ($db) {
$this->db = $db;
}
}
...
$user = new User($db);
$user->assign('userid', 1);

Related

Clarify a line/s --> setting sql data into object variables

This is my first question here and I will try to clarify it as much as possible.
I am a begginer and I am going through lynda - beyond PHP MySQL lessons when I got to this part.
Code is working just fine, I just need better explanation for myself to the line that is commented in a code.
require_once('database.php');
class User {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all() {
return self::find_by_sql("SELECT * FROM users");
}
/////
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$user_array = array();
while ($row = $database->fetch_array($result_set)) {
$user_array[] = self::instantiate($row);
}
return $user_array;
}
And finaly lines that i almost understand :)
private static function instantiate($row) {
$user = new self;
foreach($row as $attribute=>$value){
if($user->has_attribute($attribute)) {
$user->$attribute = $value; /// THIS LINE BUGS ME
}
}
return $user;
}
private function has_attribute($attribute) {
$user_vars = get_object_vars($this);
return array_key_exists($attribute, $user_vars);
}
}
So I think I don't understand array_key_exists which returns TRUE or FALSE, in my case its true, but then line $users->$attributes =$value ; makes no sense for me,
So, I check if keys from fetch array MATCH variable names from object,
if($user->has_attribute($attribute)) { //and then this is true,perform nxt line
$user->$attribute = $value; // i got match of attribute above,how does it put values in $user_vars???
I know it says something like " if user has same attribute as key from that fetch array then put into that same attribute value of that attribute $value but i just dont see how it is done when i never returned object variables
Thank you for your time !
edit:
class variables names are equal to names of column_names from database
The User class has public attributes $id, $username, $password, etc. That means that you can assign values to the attributes in the following form:
$u = new User;
$u->id = 123;
$u->username = 'username';
and using dynamic property names:
$prop = 'id';
$u->$prop = 123;
$prop = 'username';
$u->$prop = 'username';
This is just the thing that happens in the lines that you don't understand:
if ($user->has_attribute($attribute)) {
$user->$attribute = $value;
The has_attribute method fetches all attributes of the $user object with get_object_vars function. The latter fetches the object properties as an array:
$user_vars = get_object_vars($this);
/* i.e.
$user_vars = array (
'id' => ...,
'username' => ...,
...
);
*/
Then the has_attribute method checks if the given $attribute key exists in the array of properties:
return array_key_exists($attribute, $user_vars);
If it exists (true), the $attribute property is assigned to $value.

oop model Base class design : static and non-static data access

I am trying to make a base class ... tiny framework if you will just for practice
So I start with example of child class because it has less code !!
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
function __construct(){
$this->table_name = 'users';
$this->set_cols(get_class_vars('User'));
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
Here is my Base class
class Base {
protected $table_name ;
protected $table_columns ;
protected function set_cols($cols){
unset($cols['table_name']);
unset($cols['table_columns']);
$this->table_columns = array_keys($cols);
}
public function insert(){
$colums = $values = array();
foreach($this->table_columns as $col )
{
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSTER INTO ".$this->table_name ." ($colums)
VALUES ($values) ";
}
}
Here is the problem , I want to make filter or get method (basically reading from database) static and then return an array of objects from database data
class Base{
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
$export = array();
$class = get_called_class();
foreach($query_result as $q )
{
$obj = new $class;
foreach($this->table_columns as $col )
$obj->$col = $q[$col];
$export[] = $obj;
}
return $export;
}
}
$users = User::filter(['username'=>'jason' , 'email'=>'j#gmail.com']);
Here is the problem , with filter as static function __construct in User class will not get called and table_columns, table_name will be empty
also in the filter method I can't access them anyway because they are not static ... I can make a dummy User object in the filter method and solve this problems but somehow it doesn't feel right
Basically I have a design problem any suggestion is welcomed
The problem is that the static object is not really "created" when you run statically.
If you want the constructor to run, but still in a static sort of way, you need a "singleton". This is where the object is created once and then you can re-use. You can mix this technique in a static and non-static way (as you're actually creating a "global" object that can be shared).
An example is
class Singleton {
private static $instance;
public static function getInstance() {
if (null === static::$instance) {
self::$instance = new static();
}
return self::$instance;
}
}
$obj = Singleton::getInstance();
Each time this gets the same instance and remembers state from before.
If you want to keep your code base with as few changes as possible, you can create yourself an "initialized" variable statically - you just need to remember to call it in each and every function. While it sounds great, it's even worse than a Singleton as it still remembers state AND you need to remember the init each time. You can, however, use this mixed with static and non-static calls.
class notASingletonHonest {
private static $initialized = false;
private static function initialize() {
if (!self::$initialized) {
self::$initialized = true;
// Run construction stuff...
}
}
public static function functionA() {
self::$initialize();
// Do stuff
}
public static function functionB() {
self::$initialize();
// Do other stuff
}
}
But read a bit before you settle on a structure. The first is far better than the second, but even then if you do use it, ensure that your singleton classes can genuinely be ran at any time without reliance on previous state.
Because both classes remember state, there are many code purists that warn you not to use singletons. You are essentially creating a global variable that can be manipulated without control from anywhere. (Disclaimer - I use singletons, I use a mixture of any techniques required for the job.)
Google "php Singleton" for a range of opinions and more examples or where/where not to use them.
I agree with a lot of your premises in your code and design. First - User should be a non static class. Second - Base base should have a static function that acts a factory for User objects.
Lets focus on this part of your code inside the filter method
1 $query_result = "SELECT * FROM ".$this->table_name ." WHERE $query_condition ";
2 $export = array();
3
4
5 $class = get_called_class();
6 foreach($query_result as $q )
7 {
8 $obj = new $class;
9
10 foreach($this->table_columns as $col )
11 $obj->$col = $q[$col];
12
13 $export[] = $obj;
14
15 }
The issue is that lines 1 and 10 are trying to use this and you want to know the best way to avoid it.
The first change I would make is to change protected $table_name; to const TABLE_NAME like in this comment in the php docs http://php.net/manual/en/language.oop5.constants.php#104260. If you need table_name to be a changeable variable, that is the sign of bad design. This will allow you change line 1 to:
$class = get_called_class()
$query_result = "SELECT * FROM ". $class::TABLE_NAME . "WHERE $query_condition";
To solve the problem in line 10 - I believe you have two good options.
Option 1 - Constructor:
You can rewrite your constructor to take a 2nd optional parameter that would be an array. Your constructor would then assign all the values of the array. You then rewrite your for loop (lines 6 to 15) to:
foreach($query_result as $q)
{
$export[] = new $class($q);
}
And change your constructor to:
function __construct($vals = array()){
$columns = get_class_vars('User');
$this->set_cols($columns);
foreach($columns as $col)
{
if (isset($vals[$col])) {
$this->$col = $vals[$col];
}
}
}
Option 2 - Magic __set
This would be similar to making each property public, but instead of direct access to the properties they would first run through a function you have control over.
This solution requires only adding a single function to your Base class and a small change to your current loop
public function __set($prop, $value)
{
if (property_exists($this, $prop)) {
$this->$prop = $value;
}
}
and then change line 10-11 above to:
foreach($q as $col => $val) {
$obj->$col = $val
}
Generally it is a good idea to seperate the logic of storing and retrieving the data and the structure of the data itself in two seperate classes. A 'Repository' and a 'Model'. This makes your code cleaner, and also fixes this issue.
Of course you can implement this structure in many ways, but something like this would be a great starting point:
class Repository{
private $modelClass;
public function __construct($modelClass)
{
$this->modelClass = $modelClass;
}
public function get($id)
{
// Retrieve entity by ID
$modelClass = $this->modelClass;
return new $$modelClass();
}
public function save(ModelInterface $model)
{
$data = $model->getData();
// Persist data to the database;
}
}
interface ModelInterface
{
public function getData();
}
class User implements ModelInterface;
{
public int $userId;
public string $userName;
public function getData()
{
return [
"userId" => $userId,
"userName" => $userName
];
}
}
$userRepository = new Repository('User');
$user = $userRepository->get(2);
echo $user->userName; // Prints out the username
Good luck!
I don't think there is anything inherently wrong with your approach. That said, this is the way I would do it:
final class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
protected static $_table_name = 'users';
protected static $_table_columns;
public static function getTableColumns(){
if( !self::$_table_columns ){
//cache this on the first call
self::$_table_columns = self::_set_cols( get_class_vars('User') );
}
return self::$_table_columns;
}
public static function getTableName(){
return self::$_table_name;
}
protected static function _set_cols($cols){
unset($cols['_table_name']);
unset($cols['_table_columns']);
return array_keys($cols);
}
}
$u = new User;
$u->username = 'jason';
$u->email = 'j#gmail.com';
$u->insert();
And then the base class, we can use Late Static Binding here static instead of self.
abstract class Base {
abstract static function getTableName();
abstract static function getTableColumns();
public function insert(){
$colums = $values = array();
foreach( static::getTableColumns() as $col ){
if(!$this->$col) continue ;
$values[] = $this->$col ;
$colums[] = $col ;
}
$values = implode(',' , $values);
$colums = implode(',' , $colums);
echo $sql = "INSERT INTO ". static::getTableName() ." ($colums) VALUES ($values) ";
}
static function filter($conditions =array()){
$query_condition = $conditions ; // some function to convert array to sql string
$query_result = "SELECT * FROM ".static::getTableName() ." WHERE $query_condition ";
$export = array();
$columns = static::getTableColumns(); //no need to call this in the loop
$class = get_called_class();
foreach($query_result as $q ){
$obj = new $class;
foreach( $columns as $col ){
$obj->$col = $q[$col];
}
$export[] = $obj;
}
return $export;
}
}
Now on the surface this seems trivial but consider this:
class User extends Base {
public $id ;
public $username ;
public $email ;
public $password ;
final public static function getTableName(){
return 'users';
}
final public static function getTableColumns(){
return [
'id',
'username',
'email',
'password'
];
}
}
Here we have a completely different implementation of those methods from the first Users class. So what we have done is force implementation of these values in the child classes where it belongs.
Also, by using methods instead of properties we have a place to put custom logic for those values. This can be as simple as returning an array or getting the defined properties and filtering a few of them out. We can also access them outside of the class ( proper like ) if we need them for some other reason.
So overall you weren't that far off, you just needed to use static Late Static Binding, and methods instead of properties.
http://php.net/manual/en/language.oop5.late-static-bindings.php
-Notes-
you also spelled Insert wrong INSTER.
I also put _ in front of protected / private stuff, just something I like to do.
final is optional but you may want to use static instead of self if you intend to extend the child class further.
the filter method, needs some work yet as you have some array to string conversion there and what not.

PHP Class get Global Variable

I am using https://github.com/seaofclouds/tweet
I want to pass index.php?consumer_key=xxx.
After passing this I want to get in the PHP class but i am getting error.
Here is the Code below. Full Code: http://pastebin.com/gCzxrhu4
//$consumer_key = $_GET['consumer_key'];
class ezTweet {
private $consumer_key = $consumer_key; // getting error
private $consumer_key = 'xxxxx'; // working
private $consumer_secret = 'xxxx';
//other things
}
Please Help.
A class is a stand-alone, re-usable and portable unit of code.
Therefore, it should never, ever, under any circumstances, rely on GLOBAL variables to initialize its properties or do its job.
If you need a class to have access to a value, pass that value to the class, either through the constructor or a setter method:
class EzTweet
{//class names start with UpperCase, and the { goes on the next line
private $consumer_key = null;//initialize to default, null
public function __construct($cKey = null)
{//pass value here, but default to null -> optional
$this->consumer_key = $cKey;//set value
}
public function setConsumerKey($cKey)
{
$this->consumer_key = $cKey;//set value later on through setter
return $this;
}
}
//use:
$ezTwitter = new EzTwitter();
if (isset($_GET['consumer_key']))
$ezTwitter->SetConsumerKey($_GET['consumer_key']);//set value
That's what I'd do, anyways. BTW: please check, and try to stick to, the coding standards.
Update:
It turns out you already have a constructor. Fine, just change it a bit to:
public function __construct($cKey = null)//add argument
{
$this->consumer_key = $cKey;//add this
// Initialize paths and etc.
$this->pathify($this->cache_dir);
$this->pathify($this->lib);
$this->message = '';
// Set server-side debug params
if ($this->debug === true)
error_reporting(-1);
else
error_reporting(0);
}
You can't set the property class value with a $variable, in this case you need before construct your class.
class ezTweet
{
private $consumer_key = '';
private $consumer_secret = 'xxxx';
public function __construct($consumer_key)
{
if (!is_string($consumer_key) || !strlen(trim($consumer_key))) {
throw new \InvalidArgumentException('"consumer_key" cannot be empty!');
}
$this->consumer_key = $consumer_key;
}
public function getConsumerKey()
{
return $this->consumer_key;
}
}
$consumer_key = (isset($_GET['consumer_key']) ? $_GET['consumer_key'] : null);
try {
$ezTweet = new ezTweet($consumer_key);
// [...]
}
catch (\InvalidArgumentException $InvalidArgumentException) {
echo $InvalidArgumentException->getMessage();
}

HOW to get $_POST variable into my CLASS?

Probably a newbie question, but then I'm learning on the fly:
Within the following code, I need to name $targetname and $imagelocation come from the $_POST variable coming in... I KNOW I can't define these variables properly the way I'm trying to, but am a bit stumped... help anyone?
class PostNewTarget{
//Server Keys
private $access_key = "123456";
private $secret_key = "142356";
private $targetName = $_POST['the_target'];
private $imageLocation = $_POST['the_image'];
function PostNewTarget(){
$this->jsonRequestObject = json_encode( array( 'width'=>300, 'name'=>$this->targetName , 'image'=>$this->getImageAsBase64() , 'application_metadata'=>base64_encode($_POST['myfile']) , 'active_flag'=>1 ) );
$this->execPostNewTarget();
}
...
Pass into the method:
function PostNewTarget($targetName, $imageLocation)
Then call with:
PostNewTarget($_POST['the_target'], $_POST['the_image'])
You could possibly add in the constructor, but I wouldn't:
public function __construct() {
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
}
You need to initialize first your class properties
You can set $_POST values to your class properties when you create your class object using constructor, or you can set just when you need to get these values, I made it in your example
class PostNewTarget{
//Server Keys
private $access_key = "123456";
private $secret_key = "142356";
private $targetName = "";
private $imageLocation = "";
//you can give class variables values in the constructor
//so it'll be setted right when object creation
function __construct($n){
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
}
function PostNewTarget(){
//or you set just only when you need values
$this->targetName = $_POST['the_target'];
$this->imageLocation = $_POST['the_image'];
$this->jsonRequestObject = json_encode( array( 'width'=>300, 'name'=>$this->targetName , 'image'=>$this->getImageAsBase64() , 'application_metadata'=>base64_encode($_POST['myfile']) , 'active_flag'=>1 ) );
$this->execPostNewTarget();
}
}
Treat it as a normal variable and put it in a constructor or mutator or argument of a function if it's only needed in that function. Here is an example using a constructor, but the logic is the same in every case.
class Example {
public $varFromPOST;
public $name
public function __construct($var, $name) {
$this->varFromPOST = $var
$this->name = $name
}
}
Then in your index.php:
$_POST['foo'] = 100;
$userName = 'Bob';
$Example = new Example($_POST['foo'], $userName);
Seems straightforward, if I didn't misunderstand your question.

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
//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?
?>
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. 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:
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.
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.
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.
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.
Mandate that the data for you User object is provided as:
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.
Make them public members:
class user
{
public $first_name;
function __construct()
{
$this->first_name = $_SESSION['first_name'];
}
}
$user = new user();
echo $user->first_name;
Sidenote: the constructor has no return value, i.e. return false does not have the effect you probably intended.
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.
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, e.g.
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;
}
}
}
?>
You can also save the user object in the $_SESSION variable after you have created it initially.
<?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;
?>

Categories