OOP with sessions - php

Let's say I have a class called product which has 2 properties, pid and quantity.
Now, I want to make a session that will hold an array of this class. Code example:
<?php
public class product{
public $quantity;
public $pid;
public function __construct($pid,$qty){
$this->$pid = $pid;
$this->$quantity = $qty;
}
// some methods ....
}
session_start();
$_SESSION['products'][] = new product(103,10);
$_SESSION['products'][] = new product(87,6);
?>
Few questions about this:
Is my way of declaring the sessions is correct? I haven't typed something like $_SESSION['product'] = new array(); I already added objects to it.
When I will want to read the session product, will I have to import the class product to the page in order to read it and get an access to the quantity and the pid properties?
Code example:
session_start();
echo $_SESSION['products'][0]->$pid; // should echo "103" (according the the code exmaple above)
// OR I will have to do it like this:
require_once 'product.inc.php';
session_start();
echo $_SESSION['products'][0]->$pid; // should echo "103"
3.when I access a public property, do I have to access it like this: $this->$prop_name OR $this -> prop_name (difference is with the $ sign)

if you define a variable like $var = array(); it will wipe the previous array.
sessions are available throughout your domain/sub-domain, so as long as you have called session_start() before you access the session variable you're covered.
when you say public property are you referring to the class or the method? If you want to access the method inside itself to refer to it like $this->myFunction = $object; if you want to access the method outside itself but inside the class you do it using SELF::$object = new myFunction();
see this: When to use self over $this?
and this: http://php.net/manual/en/language.oop5.php
hope this helps.

Is my way of declaring the sessions is correct?
Yes. Once you have executed the session_start() the $_SESSION array will exist and be populated with data if any has been saved into previously.
When I want to read the session product, will I have to import the class product to the page in order to read it and get an access to the quantity and the pid properties?
Yes, if you have methods you need to have the class declared in order to use them.
There is a better way of dehydrating and rehydrating a class. That is serialize() and unserialize(). It takes care of all the public, protected and private data, and it also stores the class name. It does not save the methods of course.
Here is some sample code using your original example as a start point. You can run it in your browser to see the results
file product.class.php
<?php
class product{
public $quantity;
public $pid;
private $a = 99;
protected $b = 88;
public function __construct($p,$q){
$this->pid = $p;
$this->quantity = $q;
}
public function show() {
echo '<pre>SHOW '. $this->pid . '</pre>';
}
}
?>
file tst99.php
require_once( 'product.class.php' );
session_start();
$p1 = new product(103,10);
$p2 = new product(87,6);
unset( $_SESSION['products'] );
$_SESSION['products'][] = serialize($p1);
$_SESSION['products'][] = serialize($p2);
echo 'Dehydrated class'.PHP_EOL;
echo '<pre>' . print_r( $_SESSION, TRUE ) . '</pre>';
?>
file tst99a.php
<?php
session_start();
require_once('product.class.php');
echo '<pre>' . print_r( $_SESSION, TRUE ) . '</pre>';
echo 'Rehydrated class'.PHP_EOL;
$np1 = unserialize($_SESSION['products'][0]);
$np2 = unserialize($_SESSION['products'][1]);
echo '<pre>' . print_r( $np1, TRUE ) . '</pre>';
echo '<pre>' . print_r( $np2, TRUE ) . '</pre>';
$np1->show();
$np2->show();
Run tst99.php first and then tst99a.php to see that the class gets fully rehydrated.

Related

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

Accessing properties of a class

I'm coding a small piece for a larger project that will read a CSV file and store the information in a class. I'm storing each instance of the class in an array.
So far, all I'm trying to do is read each line of the CSV, create a new class instance with that info, and then display the info using a class function I created.
I have two questions:
first, when building the constructor, I originally tried using $this->$property but I got undefined variable errors for each property when I did that. I took out $this and it seemed to work alright. I'm wondering why $this didn't work there?
And now the error that I'm having is an undefined variable error for each time I try to access a variable to print it out in the displayInfo() function of my class. I don't understand how the variable is undefined, they are properties of the class and they were initialized using the constructor.
Here's my code:
<?php
class Course {
public $crn;
public $title;
public $instructor;
public $section;
public $location;
public $time;
public $days;
function __construct($arg_crn, $arg_title, $arg_instructor, $arg_section, $arg_location, $arg_time, $arg_days) {
$crn = $arg_crn;
$title = $arg_title;
$instructor = $arg_instructor;
$section = $arg_section;
$location = $arg_location;
$time = $arg_time;
$days = $arg_days;
}
public function displayInfo() {
echo ("\n");
echo $crn;
echo (", ");
echo $title;
echo (", ");
echo $instructor;
echo (", ");
echo $section;
echo (", ");
echo $location;
echo (", ");
echo $time;
echo (", ");
echo $days;
echo ("<br/>");
}
}
?>
<?php
$fileName = "testCSV.txt";
$fp = fopen($fileName, "r");
$index = 0;
// get the next line of the CSV: this contains the headers
$fields = fgetcsv($fp);
// get the next line of the CSV, which contains the first course information
// $fields is an array holding each field of the line (where a field is separated by commas)
$fields = fgetcsv($fp);
while($fields) {
// if at the end of the file, fgetcsv returns false and the while loop will not execute
// the fields in the file are saved into the following indices in fields:
// 0: CRN
// 1: Title
// 2: Instructor
// 3: Section
// 4: Location
// 5: Time
// 6: Days
// add a new course to the array of courses using the information from fields
$Courses[$index] = new Course($fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5], $fields[6]);
$Courses[$index]->displayInfo();
// get the next line and increment index
$fields = fgetcsv($fp);
$index++;
}
?>
As Mark Baker mentioned that instance variable can be accesses using $this->crn, follow the same & read some tutorials on OOPS in PHP as you are too new to this to ask anything here.
You tried accessing properties using $this->$property, which should be $this->property.
Some tutorials:
http://php.net/manual/en/language.oop5.php
http://www.tutorialspoint.com/php/php_object_oriented.htm

Dynamic global array in codeigniter

I want a global array that I can access through controller functions, they can either add or delete any item with particular key. How do I do this? I have made my custom controller 'globals.php' and added it on autoload library.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$notification_array = array();
$config['notification'] = $notification_array;
?>
following function on controller should add new item to my array
function add_data(){
array_unshift($this->config->item('notification'), "sample-data");
}
after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client.
function send_json()
{
header('content-type: application/json');
$target = $this->config->item('notification');
echo json_encode($target);
}
But my client always gets empty array. How can I make this happen? Please help.
Hi take advantage of OOP, like this
// put MY_Controller.php under core directory
class MY_Controller extends CI_Controller{
public $global_array = array('key1'=>'Value one','key2'=>'Value2'):
public function __construct() {
parent::__construct();
}
}
//page controller
class Page extends MY_Controller{
public function __construct() {
parent::__construct();
}
function send_json()
{
header('content-type: application/json');
$target = $this->global_array['key1'];
echo json_encode($target);
}
}
One solution I came up is to use session, its easy to use and its "fast" you need to do some benchmarking.
As I commented on both answers above/below there is no way you get same data in different controllers just because with each request everything is "reset", and to get to different controller you need to at least reload tha page. (note, even AJAX call makes new request)
Note that sessions are limited by size, you have a limit of 4kb (CodeIgniter stores session as Cookie) but wait, there is way around, store them in DB (to allow this go to config file and turn it on $config['sess_use_database'] = TRUE; + create table you will find more here)
Well lets get to the answer itself, as I understand you tried extending all your controllers if no do it and place some code in that core/MY_Controller.php file
as follows:
private function _initJSONSession() { //this function should be run in MY_Controller construct() after succesful login, $this->_initJSONSession(); //ignore return values
$json_session_data = $this->session->userdata('json');
if (empty($json_session_data )) {
$json_session_data['json'] = array(); //your default array if no session json exists,
//you can also have an array inside if you like
$this->session->set_userdata($ses_data);
return TRUE; //returns TRUE so you know session is created
}
return FALSE; //returns FALSE so you know session is already created
}
you also need these few functions they are self explainatory, all of them are public so you are free to use them in any controller that is extended by MY_Controller.php, like this
$this->_existsSession('json');
public function _existsSession( $session_name ) {
$ses_data = $this->session->userdata( $session_name );
if (empty( $ses_data )) return FALSE;
return TRUE;
}
public function _clearSession($session_name) {
$this->session->unset_userdata($session_name);
}
public function _loadSession($session_name) {
return (($this->_existsSession( $session_name )) ? $this->session->userdata($session_name) : FALSE );
}
the most interesting function is _loadSession(), its kind of self explainatory it took me a while to fully understand session itself, well in a few words you need to get (load) data that are in session already, do something with it ([CRUD] like add new data, or delete some) and than put back (REWRITE) all data in the same session.
Lets go to the example:
keep in mind that session is like 2d array (I work with 4+5d arrays myself)
$session['session_name'] = 'value';
$session['json'] = array('id' => '1', 'name' => 'asok', 'some_array' => array('array_in_array' => array()), 'etcetera' => '...');
so to write new (rewrite) thing in session you use
{
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession($session_name);
//manipulate with array as you wish here, keep in mind that your variable is
$session_data[$session_name]['id'] = '2'; // also keep in mind all session variables are (string) type even (boolean) TRUE translates to '1'
//or create new index
$session_data[$session_name]['new_index'] = FALSE; // this retypes to (string) '0'
//now put session in place
$this->session->set_userdata($session_data);
}
if you like to use your own function add_data() you need to do this
well you need to pass some data to it first add_data($arr = array(), $data = ''){}
eg: array_unshift( $arr, $data );
{
//your default array that is set to _initJSONSession() is just pure empty array();
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession( $session_name );
// to demonstrate I use native PHP function instead of yours add_data()
array_unshift( $session_data[$session_name], 'sample-data' );
$this->session->set_userdata( $session_data );
unset( $session_data );
}
That is it.
You can add a "global" array per controller.
At the top of your controller:
public $notification_array = array();
Then to access it inside of different functions you would use:
$this->notification_array;
So if you want to add items to it, you could do:
$this->notification_array['notification'] = "Something";
$this->notification_array['another'] = "Something Else";

php pdo in class + best method to display return array

I have the following class:
<?php
class photos_profile {
// Display UnApproved Profile Photos
public $unapprovedProfilePhotosArray = array();
public function displayUnapprovedProfilePhotos() {
$users = new database('users');
$sql='SELECT userid,profile_domainname,photo_name FROM login WHERE photo_verified=0 AND photo_name IS NOT NULL LIMIT 100;';
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$unapprovedProfilePhotosArray = $rows;
echo 'inside the class now....';
foreach($rows as $row) {
echo $row['userid'];
}
}
}
I can display the data successfully from the foreach loop.
This is a class that is called as follows and want to be able to use the array in the display/view code. This why I added the "$unapprovedProfilePhotosArray = $rows;" but it doesn't work.
$photos_profile = new photos_profile;
$photos_profile->displayUnapprovedProfilePhotos();
<?php
foreach($photos_profile->unapprovedProfilePhotosArray as $row) {
//print_r($photos_profile->unapprovedProfilePhotosArray);
echo $row['userid'];
}
?>
What is the best way for me to take the PHP PDO return array and use it in a view (return from class object). I could loop through all the values and populate a new array but this seems excessive.
Let me know if I should explain this better.
thx
I think you're missing the $this-> part. So basically you're creating a local variable inside the method named unapprovedProfilePhotosArray which disappears when the method finishes. If you want that array to stay in the property, then you should use $this->, which is the proper way to access that property.
...
$pds=$users->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
$this->unapprovedProfilePhotosArray = $rows;
...

PHP getter method question

Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details

Categories