User class - 'load' data - php

<?php
class User {
private $id;
private $username;
public function __construct($id = null) {
$this->id = $id;
if (!is_null($this->id)) {
$this->load();
}
}
public function load() {
}
}
?>
In the 'load' method I am going to load all the information from the current user (id) But I wonder how is the best way to load all info. I could grab all data and then just assign all private variables, but I assume there must be another "cheaper" way to get all the data so I can use as such
$this->variable;
And not have to ASSIGN every single data row, I select in the load method. How?

I am assuming the following:
Each User object represents 1 row in your database
You can retrieve information for your user in an associative array:
$user = array('name' => 'John', 'age' => 20);
Then perhaps using variables variables could be a viable solution in your load() method:
foreach($user as $key => $userData){
$this->$$key = $userData; //Note the use of variables variable
}

You can assign multiple variables like this in php:
private function getUserData() {
return array("42", "JohnDoe");
}
public function load() {
list($this->id, $this->username) = getUserData();
}

Related

method does not get passed when passing the class? PHP

What I want to ask is,
let's say I have a class Info and there's a getter in the info called getABC()
In a controller I assigned something like
$info = new Info();
$variable['info'] =$info;
and $variable is being passed into the view.
In the view, am I able to use something like $variable['info']->getABC() ?
I know I can just test it out myself, and failed saying something like it did not exist and $variable['info'] does show something though.
I just want to make sure that $variable['info']->getABC() is suppose to NOT work or it should but I am just doing something wrong that's why I couldn't get what's needed.
actual code below........
Class
class CreditCardPayment{
private $_card_type = '';
private $_card_number = '';
private $_card_number_last_4 = '';
public function setCardType($v)
{
$this->_card_type = $v;
return $this;
}
public function setCardNumber($v)
{
$this->_card_number = $v;
return $this;
}
public function setCardNumberLast4($v) {
$lastFourDigits = substr($v, -4);
$output = 'xxxx-xxxx-xxxx-' . $lastFourDigits;
$this->_card_number_last_4 = $output;
return $this;
}
public function getCardType() {
return $this->_card_type;
}
public function getCardNumber() {
return $this->_card_number;
}
public function getCardNumberLast4() {
return $this->_card_number_last_4;
}
}
and in Controller let's say when it's successful....it'll be something like this where $creditCardPayment = new CreditCardPayment and I tried var_dump($creditCardPayment) that definitely info is all filled and of course those are private variables so I had to use the getter retrieve them.
Controller
$ordermess['creditCardPaymentInfo'] = $creditCardPayment;
\Yii::$app->session->set('ordermess', $ordermess);
$this->redirect('/pay/completed');
then in my view...I did this as testing
<?php
echo '<pre>';
echo ($ordermess['creditCardPaymentInfo']->getCardNumberLast4());
echo '</pre>';
die;
?>
then when I load the page I would get error.
Call to a member function getCardNumberLast4() on a non-object
Yes. It is supposed to work. If there is sanitization code in the function assigning variables to the view, it could be converting the object to an array.

Access private static class property from Ajax

I have a class similar to this:
class My_Class {
private static $array = null;
private static $another_array = null;
private function __construct() {
self:$another_array = array( 'data' );
}
// This gets executed from jQuery Ajax when user clicks a button
public static function process_ajax() {
self::generate_html();
}
private static function generate_html() {
if ( ! self::$array ) {
self::$array = array( 'some data' );
}
}
// This gets executed when user is trying to save Ajax generated form
public static function save_ajax_form() {
print_r( self::$another_array ); // prints [0] => 'data'
self::validate_data();
}
private static function validate_data() {
// WHY DOES THIS EVALUATE TRUE?
if ( ! is_array( self::$array ) ) {
}
}
}
How can I access My_Class::$array property from an Ajax call?
Even though you are declaring the variable static it is going to be initialized to null on every request - PHP is "stateless" in this way, static variables will not persist accross requests. Since you do want to persist the value you will need to use something like $_SESSION, APC or memcached to hold the value of $array.
When your ajax calls save_ajax_form() it immediately then calls validate_data(). The $array variable is still initialized to null since the call to generate_html() happened in a different request, so the check to see if it is not an array will return true.
See: Does static variables in php persist across the requests?
Obviously you could either change the scope declaration from private to public, or if you want to keep private, add a public accessor:
public function getArray()
{
self::process_ajax();
return self::$array;
}

Set Array as Public Attribute

class Student{
$db_fields = array('id','firstname','lastname')
}
Is there any way to set $db_fields array into a public variable/attribute without typing it manually like:
class Student{
$db_fields = array('id','firstname','lastname')
public $id;
public $firsname;
public $last;
}
?
I'm trying to set it using foreach but I can't make it done.
class Student{
public $db_fields;
public $id;
public $firsname;
public $last;
public function __construct($data){
$this->db_fields = $data;
}
}
$students = new Student(array('id','firstname','lastname'));
You can set it this way ..
or this way..
class Student{
public $db_fields;
public $id;
public $firsname;
public $last;
public function set_db_fields($data){
$this->db_fields = $data;
}
}
$students = new Student();
$students->set_db_fields(array('id','firstname','lastname'));
The idea is when you call that class to set Those variables with some function..
1st way is to use the constructor and 2nd way is to write 1 function only for that..
The 3rd way is as #PLB replayed with magic functions.
Yes, you can use magic method __get and __set (These methods are used to access inaccessible variables of instance. You can get further information in documentation) in your class Student.
public function __get($name) {
return $this->{$name};
}
public function __set($name, $value){
$this->{$name} = $value;
}
Now you can use it:
$obj = new Student();
$obj->db_fields = array(1,2,3); //Assign private variable.
var_dump($obj->db_fields); //Get private variable.
The only way to access an array's variable is through the array (to my knowledge) as such:
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
echo $db_fields->id; // would print 5.
What you're saying you want is:
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
echo $id; // would print 5 but that is not possible
The only instance where this works is if the array you're talking about is $_POST and $_GET with register globals, but to my knowledge it is not possible to do this with any array (and in fact it is usually not recommended to do it even with the $_POST and $_GET arrays).
EDIT:
You can actually use the extract() function on your array.
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
extract($db_fields);
echo $id; // if I'm not mistaken, that should work

how can I get around no arrays as class constants in php?

I have a class with a static method. There is an array to check that a string argument passed is a member of a set. But, with the static method, I can't reference the class property in an uninstantiated class, nor can I have an array as a class constant.
I suppose I could hard code the array in the static method, but then if I need to change it, I'd have to remember to change it in two places. I'd like to avoid this.
You can create a private static function that will create the array on demand and return it:
class YourClass {
private static $values = NULL;
private static function values() {
if (self::$values === NULL) {
self::$values = array(
'value1',
'value2',
'value3',
);
}
return self::$values;
}
}
I put arrays in another file and then include the file wherever I need it.
I am having a really really hard time understanding your question. Here is essentially what I understood:
I need to maintain a proper set, where
no two elements are the same.
PHP does not have a set type, not even in SPL! We can emulate the functionality of a set but any solution I can think of is not pleasant. Here is what I think is the cleanest:
<?php
class Set {
private $elements = array();
public function hasElement($ele) {
return array_key_exists($ele, $elements);
}
public function addElement($ele) {
$this->elements[$ele] = $ele;
}
public function removeElement($ele) {
unset($this->elements[$ele]);
}
public function getElements() {
return array_values($this->elements);
}
public function countElements() {
return count($this->elements);
}
}
Example usage:
<?php
$animals = new Set;
print_r($animals->getElments());
$animals->addElement('bear');
$animals->addElement('tiger');
print_r($animals->getElements());
$animals->addElement('chair');
$animals->removeElement('chair');
var_dump($animals->hasElement('chair'));
var_dump($animals->countElements());

Dynamically picking variable from a class

I'm trying to get data from a class in php5, where the data in the class is private and the calling function is requesting a piece of data from the class. I want to be able to gain that specific piece of data from the private variables without using a case statement.
I want to do something to the effect of:
public function get_data($field)
{
return $this->(variable with name passed in $field, i.e. name);
}
You could just use
class Muffin
{
private $_colour = 'red';
public function get_data($field)
{
return $this->$field;
}
}
Then you could do:
$a = new Muffin();
var_dump($a->get_data('_colour'));
<?php
public function get_data($field)
{
return $this->{$field};
}
?>
You may want to look at the magical __get() function too, e.g.:
<?php
class Foo
{
private $prop = 'bar';
public function __get($key)
{
return $this->{$key};
}
}
$foo = new Foo();
echo $foo->prop;
?>
I would be careful with this kind of code, as it may allow too much of the class's internal data to be exposed.

Categories