Nasıl bir PHP sınıfı belirlenen değişkenleri kullanabilir?

5 Cevap php

PHP aşağıda bu küçük örnekte hangi kullanıcı sınıfındaki değişkenleri oluşturmak mümkün olacak ve sonra bir kullanıcı nesnesi oluşturmak nerede herhangi bir sayfada bunları kullanmak edebilmek için iyi bir yol olurdu?

<?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?

?>

5 Cevap

Lance 'cevap üzerinde durmak; sınıfın noktası verileri için bir kap başka bir şey olmak için ise, veri ile bir şey yapıyor yerine oldukça güvendesiniz. Ama OOP iyi bir temel encapsulation sadık olmaktır. Encapsulation Eğer dışarıdan gelen nesnenin iç ayrıntılarını gizlemek ve arabirim yöntemleri var ile yalnızca dış erişim alanları izin verdiğini, diğer şeyler arasında, anlamına gelir.

Diyelim Kullanıcı nesne alanları dışarıdan değiştirilemez istemiyorum diyelim, ama sadece erişilebilir, daha sonra aşağıdaki gibi bir şey ile daha iyi olacak you'ld:

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

}

Tüm dürüstlük, sen magic methods ne istediğiniz taklit ve __ set yönteminde herhangi bir istenmeyen değiştirilmesini yakalamak için kümesi olsun __ gibi ve __ kullanabilirsiniz.

Ayrıca, ben küresel bir değişken olarak oturumu kullanmak olmaz. (Ben örnekte gösterildiği gibi) Bunu yapıcısına bir argüman olarak oturum nesnesi geçmelidir. Bu gevşek bağlantı zorlar. Çünkü artık Kullanıcı nesneleri global oturum nesnesine bağlı olan, ancak herhangi bir veri içeri geçebileceğini kurucusuna geçirmeden ile sınıf daha esnek hale getirir.

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

Sen gevşek bağlantı yaymak için eldeki birkaç seçenek var ve kullanıcı biraz daha esnek nesne yapıyor.

: Eğer kullanıcı nesnesi için veri olarak sağlandığını Mandası

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

Orada birkaç diğer seçenekleri vardır, ancak bu size bazı fikirler verecektir. Umarım bu yardımcı olur.

Onları kamu üye olun:

class user
{
  public $first_name;

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


}

$user = new user();

echo $user->first_name;

Sidenote: yapıcı, hiçbir dönüş değeri yoktur, yani return false muhtemelen amaçlanan etkisi yoktur.

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');

Ya da "büyü" kullanımı __get() yöntemi, örneğin

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;

Kullanım saklamak için bağlıyor.

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

Eğer başlangıçta oluşturduktan sonra da $ _SESSION değişkeni kullanıcı nesneyi kaydedebilirsiniz.