Initializing Variables in PHP
by Amit Arora
Published: August 13, 2003
User Rating: 16,777,216.0 (256 votes)

» Code
Page Page » 1 2 3

Solution

The solution is a small function called initvar() which would intialize the variables and we need to call it once at the top of the script to tell it to which variables to intialize. It may be used like this

initvar('variable_name', 'name', 'address'); // Above line of code is equivalent as $variable_name = ''; $name = ''; $address = '';

But what we all want to intialize the variables only when they are not intialized. We don't want something like this

$str = 'Hello'; initvar('str'); echo $str; // should be equal to 'Hello' and not ''

i.e. we don't want it to re-intialize the already existing variables.

And what about passing the values ?

We would also want to pass values while intializing and give a default value to it, i.e. we should be able to pass values like this

$nbooks => 5; $my_array => array();

Now, imagine an online bookstore, wherein we allow the user to select the the number of books to be displayed on the page. Lets say we want to keep it default value of 5 books per page. So if we call the page like this showbooks.phtml, it should show 5 books. But if call it like this showbooks.phtml?nbooks=10 it should show 10 books. We can use initvar() to achieve this goal by coding like this

initvar('search_str', array( 'nbooks' => 5, 'my_array' => array() ) );

Combining SafeExtract() and initvar()

Using SafeExtract() and initvar() in combination could lead to great rapid development and reduced error. For e.g. taking the above example. (If you want to find out about SafeExtract())

SafeExtract( array( 'any' => array('nbooks'), 'post' => array('search_str') ) ); initvar('search_str', array( 'nbooks' => 5, 'my_array' => array() ); );

» Code
Page Page » 1 2 3

About

Amit Arora is web developer with expertise in developing eCommerce enabled websites for the businesses.

Contact | Resume

Subscribe to newsletter




Get Firefox

Monitored by Site24x7
Uptime