Page 1 of 1

Managing Variables in PHP Rate Topic: -----

#1 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 143
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Posted 03 March 2009 - 11:48 AM

Managing Variables in PHP

Three language constructors are used in PHP to manage variables. These are-
1.isset()
2.unset()
3.empty()

These are useful in checking the existence of a variable, undeclaring the value of a variable and in checking the value of a variable.

isset()

To check if a vriable is already declared, isset() is used. When a variable is passed through this constructor, two results are possible. If the variable is already set, then it returns boolean value true. Otherwise it returns boolean false. isset() can also be used on array elements and object properties.

Example: Use of isset() to check wheather is variable is set or not-
<?php
if(isset($username)) {
	print “$username is set.”;
}
?>



Example:Checking an array element
<?php
if(isset($age[“atik”])) {
	print “Atik is “.$age[“atik”].” years of age”;
}
?>



Example:Using isset() to check an object property
<?php
if(isset($object->property)) {
	......
}
?>


A special advantage of isset() constructor is that it can have an arbitrary amount of parameters. In that case, if all the variables are defined, only then it will return true, otherwise it will return false. This is helpful in saving a considerable amount of time when you are to check a number of input variables sent by client.

unset()

The constructor unset() is used to undeclare previously set variable. It frees the memory used by the variable being unset().

Example:Use of unset()
<?php
$username=”atik”;
unset($username);
if(isset($username)) {
	print “$username is set!”;
}
?>



The code above will return false as the variable $username is passed through the unset() constructor before it is passed through the isset() constructor.

empty()

Another constructor used in PHP to manage variable is empty(). This constructor is used to check if a variable is declared or its value is false. The empty constructor is proved to be handy when checking if a form variable has not been sent or does not contain data.

Example:Use of empty constructor
<?php
if(empty($username)) {
	print “Error: Username is not specified!”;
}
?>



Indirect Reference to Variables

A variable can be accessed by indirect reference. This is done by adding an additional $ sign at the beginning of a variable. The level of indirections can be as many as you want. This feature may be useful in some cases.

Example:Indirect variable reference
<?php
$name=”atik”;
$$name=”Author”;
pirnt $atik;
?>



Output:
Author

Here we have added an additional $ sign before the variable $name and a variable named $atik is created.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1