PHP passing variables between more function - php

I have about 30 variables that I need to pass to 3 functions e.g.
displayform() - where some form data is pulled out from DB and some needs to be entered into the form.
checkform() - which checks if all data is entered properly.
errors() - this will display errors (if any)
processform()- this process all data and store them to DB
Now I am using GLOBAL $variable; to pass those variables between functions, but than I have to declare each variable as global at the function begin and that results in a big file, so I just want to know is there a way to declare variables as globals (preferably only once) so that all functions can use them ?

You can try putting all the variables into an associative array and just passing this array between functions, like:
$omgArray = array();
$omgArray['lolVar1'] = lolVar1;
$omgArray['wowVar3'] = wowVar3;
yeaaaFunction($omgArray);
function yeaaaFunction($omgArray){
echo $omgArray['lolVar1'] . $omgArray['wowVar3'];
}

30 variables? Apart from 30 variables being horrible to maintain, having 30 global variables is even worse. You will go crazy one day...
Use an array and pass the array to the functions as argument:
$vars = array(
'var1' => 'value1',
'var2' => 'value2',
///...
);
displayform($vars);
//etc.
Learn more about arrays.

I have a similar scenario where I wrote a class lib for form handling similar to yours. I store all form data into a single array internally in the form class.
When moving form data outside the class I serialize the array into JSON format. The advantage of the JSON format (over PHP's own serialized format) is that it handles nested arrays very well. You can also convert the character set for all the form fields in one call.
In my application I store all form data as a JSON string in the database. But I guess it all depends on your needs.

You may want to read about Registry pattern, depending on your data, it may be useful or not.

Related

How to pass an object in query string in PHP

I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]

Is it better to set an object value in a function, or return a value from a function?

Lets say I have an array of data, and I want to process some function that will add or amend data in this array. e.g.
$my_data = array(
'val1' => 'my value 1',
'val2' => 'my value 2'
);
Traditionally I would pass the array or value to a function and return some data, e.g.
$my_data['val1'] = $this->get_new_var($my_data['val1']);
Well I just started doing something different which I think is better... I create the array within the $this object, like so (I am using Expression Engine):-
$this->EE->my_data = $my_data;
Then I just call a set method (rather than get) which does not need to return a value, because it sets the value within the function, e.g.
$this->set_new_var();
And within the set_new_var() function I can call the $this->EE->my_data array and manipulate it and set it as follows:
$this->EE->my_data['val1'] = $my_new_var;
So this seems to me to be cleaner, no need to pass variables to and from functions.
It also means I can set multiple values within the set function if need be, instead of returning one value from a function (or passing the entire the array and returning that).
So my question is, whether this set() method would be considered better, or should I stick to a traditional get() method.
Thanks
In my own opinion, a set() method allows me to handle the input in my own way and operate upon it, i.e. I can sanitize the input according to my use case and only pass on clean filtered input values to my function. Moreover, the set() method can be used to do more than just setting the variable. For example, in a particular use case, I may want to run a particular method or a process or even a delayed job, whenever a new value is set for a given variable (OOP). The set() method can be used to do exactly that, everytime. No need to repeat all your statements everytime such a behaviour is expected.
But, this is my own opinion.

using prototype functions for an array of object literals

I am using PHP, MySQL, and javascript. I use php to connect to my database to select appointments. I then echo them in a script tag as arrays of object literals (JSON objects):
appointment[$apptid] = {"time":"8:00", "date":"2012-02-10", "description":"testAppt"};
...
I chose to do it this way over writing an appointment "class" in case I add or remove appointment fields, however I can't figure out for the life of me how to create functions that will apply to this array of objects. Is there anyway to declare these as appointment objects and then write prototype functions without losing the properties?
I'm not 100% sure that I understand what you're after, but if I understand then maybe this is what you want:
First of all, in javascript you better use arrays in a different way than in php, so do something like:
var appointments = [];
appointments.push({"time":"8:00", "date":"2012-02-10", "description":"testAppt"});
Now, once you the array you can do something like:
function doSomething() {
alert(this.time);
}
for (var i = 0; i < appointments.length; i++) {
appointments[i].doSomething = doSomething;
}
Check out JSON.parse: http://www.json.org/js.html
Using this, you can parse your JSON strings into appointment objects that contain your variables as defined in the JSON string, with no prototyped functions.
Then, if you want to get really fancy, you can use the "reviver" parameter to pass in a function in which you could define the functions for each appointment object.

,what is the use and benefit of Serialize() function in php

I know its Generates a storable representation of a value and used to access the objects across the php files but what if i dont use this function while storing the objects.
Let's say you have some post data, but your database/persistent storage can't be modified to store the new post data in separate fields.
You could serialize your $_POST array and store it in the persistent storage you've got. It's useful for generating user-based CRUD applications. I've found the necessity of storing the POST as a "payload" of sorts quite invaluable at times.
Knowing you can do something, doesn't mean you have to use it everywhere.
That is easly explained by reading the official PHP page that states:
Generates a storable representation of a value
This is useful for storing or passing PHP values around without losing their type and structure.
Basically you can serialize an object write the string in a file and on another request you can simply read the file and unserialize it to have the final object loaded.
When you want to store or send data in a "safe" format, preserving PHP type and structure.
For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.
$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );
When you want to use the stored data, you may use the "unserialize" function:
$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );
You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)
When you unserialize an object, you must ensure to have loaded its class previously.
More at the PHP manual: http://php.net/serialize
To serialize means converting runtime variables into consistent form.
Often this is a simple string or XML representation of the code segment.
Usage:
<?php
$user = new UserObjectFromDatabase();
$data = serialize($user);
http_reqeust_send($to = "some remote server", $data);
// the remote server can now use unserialize($data) to re-construct the user object
?>
If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:
if(file_exists($thefile)) {
$data = unserialize(readfile($thefile));
} else {
$data = array(); // or anything
}
// do something with data
$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)
You can store a PHP structure in a file, session or even database. I use it for caching query results in a file or in memcache.

Help loading contstants stored in serialized array using eval() and constant()

DISCLAIMER:
Please read carefully as this is NOT a question about storing arrays in constants or simple eval() or serialize() techniques. This IS a question primarily about how constants work in PHP and why the constant() function is not working to convert a constant name into a constant value. Thanks.
BACKGROUND:
For various reasons, I started out with a flat config file for a homebrewed LAMP(PHP) CMS (in private development). Looking back this may have been misguided, and I have transitioned my variable storage into a DB table. However, the bulk of the code still depends on the CONSTs, so I use eval("define(A, B...);") to load the DB values A and B into constants. This part works fine. But it gets a bit more complicated.
PROBLEM:
The problem I'm having now is with constants in arrays (NB. NOT arrays in constants). I have a big, GLOBAL array called defaults that contains config settings in the format shown below.
Initially, I declare: <?php define('THIS_IS_A_CONSTANT', 'abcdefg'); ?> (And THIS WORKS...)
Next, I define $GLOBALS['defaults'] as the following nested array:
Array
(
'var_name' => Array
(
'display' => THIS_IS_A_CONSTANT,
'value' => 12,
'type' => 'int',
'params' => Array ( ... )
),
...
Lots more variables...
...
)
To prevent the client (who has file system access but no direct DB access but can change certain values, including most constants, via the CMS's administrative backend) from mucking up this array structure, I serialize the array structure and store that string in the DB. On each page request, I first define all the constants (stored in the DB) using the eval(define(A,B...)), then I unserialize the array above (which was serialized and stored in the DB). However, no matter what I try I cannot get the values at $GLOBALS['defaults']['var_name']['display'] to be recognized as the values that the constants contain. Instead, the constant name shows up and NOT the constant value (in other words, my output contains THIS_IS_A_CONSTANT instead of 'abcdefg'). Very frustrating, right?
I've tried something like the following (where $arr contains the unserialized array that I fetch from the DB):
foreach ($arr as $item => $contents) {
$display = isset($contents['display']) ? $contents['display'] : 1;
$value = constant("$display");
// This doesn't work, though it seems like it should
$contents['display'] = $value;
// Neither does this, no matter how much I juggle the quotation marks and backslashes
eval("\$contents['display'] = constant(\"$value\");");
// or this ...
eval("\$contents['display'] = $value;");
// or this ...
eval("\$contents['display'] = \$value;");
// or a number of other things...
}
$GLOBALS['defaults'] = $arr;
QUESTIONS:
Has anyone dealt with this kind of situation before? Can anyone advise me how to force my constants to be recognized as CONSTANTS and not strings. Do I need to serialize my array differently? Or maybe process the unserialized array differently (after retrieving it from the DB)? Is these some combination of eval() and constant() that will allow me to do this? Why are the constants within my array behaving badly while the constants I define normally are working without problem? Any help at all would be greatly appreciated, as I've been puzzling over this for a few days now and haven't come to any solutions.
All the best, Dakota.
Although eval does have its uses, this is not one of those cases. You have no idea what is being submitted to the eval at run time - and by the sounds of things you are storing something which you are then treating as code in a user-data storage location.
If the constant was defined before the array was declared then the serialized version would contain the value instead of the label. I can only assume that the value may differ depending on the context at run-time.
I would suggest that a better solution would be to roll your own macro language in PHP, e.g. something like:
<?php
global $defs;
$defs=array(
'THIS_IS_A_CONSTANT' => 'abcdefg',
'SO_IS_THIS' => 23
);
// for inline constants
foreach ($defs as $label =>$val) {
define($label, $key);
}
replacer($defs,true);
function replacer($in, $init=false;)
{
static $defs;
static $vals;
if ($init) {
$defs=array_keys($in);
$vals=array_values($in);
return count($in);
}
return str_replace($defs, $vals, $in);
// you might want to use preg_replace() with a pattern based on $defs for a neater solution
}
function fix_var(&$in)
{
if (is_array($in)) {
foreach ($in as $key=>$dummy) {
fix_var($in[$key]);
}
} else {
$in=replacer($in);
}
}
?>
C.
First, why are you evaling? From what you are saying you want the value of $GLOBALS['defaults']['var_name']['display'] to be the value of the constant THIS_IS_A_CONSTANT. You have de-serialized the string from your database and shoved in in $GLOBALS['defaults'] and the string stored the value as the constant name, not the value of the constant.
Have you tried:
<?php
define('THIS_IS_A_CONSTANT', 'abcdefg');
$value = constant($GLOBALS['defaults']['var_name']['display']);
//$value should now be abcdefg not THIS_IS_A_CONSTANT
$GLOBALS['defaults']['var_name']['display'] = $value;
?>
If "$GLOBALS['defaults']['var_name']['display']" does contain the string THIS_IS_A_CONSTANT then all you should need to do is pass that string to the constant funct.
Am I missing something?

Categories