retrieving contents of a class object in php - php

i am trying to get the contents of another class object into php code.
a class object contains
$Raiwind = new gridcell();
$Raiwind->place="raiwind";
$Raiwind->latitude="31.4279";
$Raiwind->spatial[] = array(
array('lda','31.4104',3),
array('ali','31.3998',3),
array('multan','31.4675',10));
$Raiwind->temporal[]=array(
array('lda',00.04),
array('ali',00.06),
array('multan',00.26),
array('dha',00.33));
$Raiwind->taxi=array(array(8899, 15.56));
now in another web page i am trying to get the taxi array contents matched with $raiwind.
how to code that.

Store the object in session.
I give you a link if you don't know how to do this.
Exemple:
//start session
session_start();
$obj = new Object(...);
//do something
$_SESSION['object']= $obj;
Now your have your object in session, and you can use it everywere in your application.
You can also serialise the object for pass it in GET or POST.
Same problem

Related

Maintain php object state

My php code creates a "School" object which is (among other functions) able to return several forms which are being ,on submit, handled by php.
Thru one of these forms i'm able to add a "SchoolClass" object to a array in the "School" object but it seems that the "School" object is recreated at some point after i add the "SchoolClass" object. This re-creation makes the array of "SchoolClass" disappear.
The functions that returns the forms are static, but the functions where "SchoolClass" objects are added to the array are not static; ("School::ShowStudentForm() and School->RegisterSchoolClass($class)")
Both the class definition and the php-script which handles the form after submit is in the same file(index.php). I had the idea that keeping both the class code and the form handling code in the same file would do the trick, but it did not make a change.
Question 1: how do i maintain the "School" object for as long as i need it?
Question 2: is it ok to create a class with only static methods and write the data directly to a file or database to avoid the whole problem or just skip the whole object approach and just use "normal" functions?
Yes, this problem is probably encounterd before and therefore also answered before but i have not been able to find a answer which i understand.
OK....i figured it out.
I can use the $_SESSION variable to store it.
Now i do like this in the start of the page:
$school = null;
if(!isset($_SESSION["school"]))
{
$school = new School;
$_SESSION["school"] = $school;
echo "New school <br>";
} else {
$school = $_SESSION["school"];
}

PHP - Reference a StdClass Object from a variable?

Maybe I am searching wrong, but I'm unable to find how to specify an Object Class in a string. Example:
I keep a list of json sites in a database, perform a foreach loop to retrieve a specific item from each site. However, each site has a different structure.
SITE 1: $result->Food->Price->Today;
SITE 2: $result->Pizza->Slice->discount;
I am trying to keep "$result->Pizza->Slice->discount" in a variable (specified in database) and return it from the class.
Sounds easy, but I'm new to class objects and all I find is how to create an object from an array.
Store this value into your database:
serialize(['Pizza', 'Slice', 'discount']);
When reading the value, unserialize it:
unserialize($value_from_db);
To retrieve the value from the JSON object use this simple function:
function retrieve_value($object, $trail) {
foreach ($trail as $name)
if (isset($object->$name))
$object = $object->$name;
else
throw new Exception("Object does not have the property $name");
return $object;
}
So you have something like this:
$value = retrieve_value(json_decode($json), unserialize($db_value));
Do not use eval(), because it is evil.
A dirty way to do this would be to json encode and decode.
$array = array([Your array]);
$obj = json_decode(json_encode($array));
Haven't tested the code though.
I guess you could store the pathing inside the database then use "eval()" with the path on the object. Just make sure you know no one can alter the pathing because eval is dangerous with un-sanitized code!
eval("\$value = \$result->{$pathvar};");
I didn't test that, but something of the sort. Of course $pathvar would be the value of the path coming from the database, whatever variable that's stored in.

PhP variable declared in a loop and I would like to store it in a global array

Im new to PHP and would like to get some advice on the following situation:
I have a file in which Im parse an XML file. My strategy has been create a "parser.php" file. Then create separate files for each tag in the XML file. Each of these separate files is a class that when instantiated will store all the attributes of that particular tag.
I have several loops in the parser that instantiate the class that corresponds with the tag when they encounter it.Once the loop is done that object is then inserted into a global array.
Here is the code:
<?php
include ('class.Food.php');
include ('class.Drink.php');
$xml = simplexml_load_file("serializedData.xml");
//Global Variables==============================================================
$FoodArray = array();
$DrinkArray = array();
$FoodObj;
$DrinkObj;
foreach($xml->children() as $child)
{
//Instantiate a Food object here and insert into the array
$FoodObj = new Food();
//Add attributes of tag to the Food object
array_push($FoodArray, $FoodObj);
}
Thus at the end of each loop there would be a food object created and that would be added to the FoodArray.
My questions are:
Do I have to explicitly call a destructor or free the object memory at the end of the loop?
Using the above syntax, will the FoodObj be stored in the FoodArray as a reference or a value
Each time the variable Food gets a different instance stored in it, does that matter when stored in the array? All the objects stored in the array go by the index number right?
Thanks
If you 'free' the Food() object at the end of the loop, you'd be killing the last reference to it you pushed into $FoodArray as well. PHP will clean up for you and delete things when they go out of scope. Since you're assigning to a global array, the scope is the whole script. So unless you explicitly take steps to delete an item from $FoodArray, the objects will be kept around until the script exits.
http://www.php.net/manual/en/language.oop5.references.php
array_push puts elements onto the end of the array, so they'll get an incrementing index number.
Try the following
$FoodArray = array();
$DrinkArray = array();
foreach($xml->children() as $child)
{
//Instantiate a Food object here and insert into the array
$FoodObj = new Food();
//Add attributes of tag to the Food object
$FoodArray[] = $FoodObj;
unset($FoodObj);
}
1) unset'ng the instance manually is good form, but unnecessary. the php garbage collector will do it for you anyways and is very efficient.
2) in the example above, $FoodArray[i] will continue to point to the instance even after $FoodObj is unset.
3) it works whether $FoodObj is local to the loop or not. But for best practice it should be.

proper way of using output of one class in another class

I am using the following code to produce an array:
// Create new customer object
$customers = new customers;
// Array of user ids
$customers->ids = array(34,23,78);
// Process customers
$customers->processCustomers();
The above code will output an array full of needed user information based on the users passed to it.
Now I need to take further action to this new customer array in the following code:
// Create new parsing object
$parseCustomers = new parse;
// Array of customer data
$parseCustomers->customers = ???????????
// Finalize new transaction
$parseCustomers->finalizeTransaction();
I need to pass the array from the first class output into the second and I'm wondering what best practice is.
This customer array can be very large at times, so ideally I wouldn't have 2 variables containing the same array at any time.
If you mean the processed array from the $customers object, you need some public method to get that data.
Let's assume you have a public method getData(). Your code would then look like this...
// Create new parsing object
$parseCustomers = new parse;
// Array of customer data
$parseCustomers->customers = $customers->getData();
// Finalize new transaction
$parseCustomers->finalizeTransaction();
There are several different ways you can handle this. Here are two:
You could return the MySQL result set from your class. I would run your query with mysql_unbuffered_query() so that it only uses up memory as you need the records.
When you grab your results, you could pass in your customers by reference:
Here's the code for #2:
// Create new parsing object
$parseCustomers = new parse;
// Array of customer data (not needed)
// $parseCustomers->customers = ???????????
// Finalize new transaction
$parseCustomers->finalizeTransaction($arrCustomers);
And your function declaration would change to this:
function finalsizeTransaction(&$arrCustomers) {
// Do your processing
}
This would allow you to use the ONE array of customers, eliminating your duplication. If you're dealing with really large data sets, so much that it could cause PHP to error out when it runs out of memory, I would use the unbuffered query method.
Hope that helps!

Using objects in Ajax calls PHP files

I have instantiated a class in my index.php file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php file.
How can I make it work? Because I donĀ“t want to create new objects, because the one I created holds all the property values I want to use.
Use the session to save the object for the next page load.
// Create a new object
$object = new stdClass();
$object->value = 'something';
$object->other_value = 'something else';
// Start the session
session_start();
// Save the object in the user's session
$_SESSION['object'] = $object;
Then in the next page that loads from AJAX
// Start the session saved from last time
session_start();
// Get the object out
$object = $_SESSION['object'];
// Prints "something"
print $object->value;
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!
Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.
mm, you should store in session, $_SESSION["someobj"] = $myobj;, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of $myobj and any contained object in it.
Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
include(whateverfilethathastheclassorincludeit.php)
$theObject = new TheObjectClass();
//do something with the object or not
$_SESSION['myobject'] = $theObject;
This is how I access the object's members in my Ajax call PHP file:
include(whateverfilethathastheclassorincludeit.php)
$theObject = $_SESSION['myobject'];
//do something with the object
If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.
You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
$myobject = new myobject();
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
global $myobject;
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.
As others have suggested, $_SESSION is the standard way to do it, in fact, that was one of the reasons, that sessions where invented to solve. Other options, i.e. serializing the object rely on the client side to hold the object and then return it untampered. Depending on the data in the object, it is not a good solution, as a) the object may include information that should not be available on the client side for security reasons and b) you will have to verify the object after receiving it.
That said, and if you still want to use the object on the client side, then JSON is an option for serializing object data, see JSON functions in PHP.
Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
$_SESSION['object'] = $object;
vs
$_SESSION['property1'] = $object->property1;
$_SESSION['property2'] = $object->property2;
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.

Categories