Oct
07
2008

PHP Basics: Language Construct

In this section of the Zend PHP 5 Certification Blog I will be refreshing my knowledge of language constructs, not to be confused with functions! even though they look like them. You should already know of or know how to use these.

Define: Language Construct

A language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of a programming language.

In PHP they have made Language Construct look like functions, this is to ease simplicity when learning PHP. We should be aware that those listed bellow are “Language Constructs”

Language Construct: echo()

Echo outputs strings to the user. Their are many methods of using echo! Its not a function so you can use parentheses echo(”test”); or not echo “test”; up to You!

You should already know about echo and its abilities, if not here are a few examples:

echo "Hello World";
 
echo "Hello World
Can be Multiple Lines";
 
echo "Hello World \nCan be Multiple Lines\n this comes with newliens too.";
 
echo "Escaping characters is done \"Like this\".";
 
// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";
 
echo "foo is $foo"; // foo is foobar
 
// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
 
// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz
 
// Some people prefer passing multiple parameters to echo over concatenation.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

Language Construct: empty()

I use this construct a lot, it checks a variable to see if it contains anything. It displays false if the variable contains 0, or even if an array is emtpy. This construct is similar to isset with a few differences:

$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is empty, or not set at all'; // True
} else {
    echo '$var is not empty'; //FALSE
}
//check out the new charictor before empty!
if (!empty($var)) {
    echo '$var is not empty'; //False
} else {
    echo '$var is empty, or not set at all'; //True
}
 
// isset difference :Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty!!';
}

Language Construct: isset()

isset determines whether a variable is set, isset only works with variables. If variable is set to NULL or has passed the unset(); construct then it will return FALSE. If a variable with data, no data, white space or 0 it will also return TRUE. This construct allows checking of multiple variables, to return true all variables must be set. isset is common place in PHP, bellow are some examples:

$var = '';
$a = "test";
$b = "anothertest";
 
if (isset($var)) { echo "This var is set so I will print.";} //True
$varset = isset($var, $a, $b); //True
$var2set = isset($var, $a, $z); //False $z not set.
 
$foo = NULL;
var_dump(isset($foo));   // FALSE
 
//Useing tenary opperator (simple if)
$sClientId = isset($_GET['client_id']) ? $_GET['client_id'] : false;

Language Construct: unset()

unset removes the data stored in a specified variable. Once executed it does not return true or false which is why isset() is used.

// destroy a single variable
unset($foo);
 
// destroy a single element of an array
unset($bar['quux']);
 
// destroy more than one variable
unset($foo1, $foo2, $foo3);

Language Construct: eval()

eval evaluates a string as PHP Code, eval() behaves as if the string being evaluated was a normal block of code. It is commonly used on user input PHP or runtime generated PHP.

It is like using the Echo () function in the sense that it outputs everything, except instead of outputting it as text, it outputs it as PHP code to be executed. One use of this is to store code in a database to execute later.
Normal Code:

for ($ord = 1; $ord < 256; ++$ord)
    printf ('%02X: %s<br>', $ord, chr ($ord));

Code Using eval:

echo eval (
    "for (\$ord = 1; \$ord < 256; ++\$ord)
        \$output .= sprintf (\"%02X: %s<br>\", \$ord, chr (\$ord));
 
    return \$output;"
);

eval returns FALSE if their is an error, if executed successfully nothing is returned but at end of your eval code you can use “return TRUE;” to force it too.

Language Construct: exit()

Exit is used to stop the script dead. You can also output an error message with the exit to display to the user why the script was terminated. The use of exit is useualy used when something goes wrong such as if unsucesfuly opening a file:

$file = fopen($filename, 'r') or exit("unable to open file ($filename)");

The error prints to the user and can also include variables. You can use exit anywhere in the script to terminate it:

exit;
exit();
exit(0);
exit('Script Terminated, Try Again?');

Language Construct: die()

die = exit. Does the same, acts the same is the same. The only reason die is in here is that PHP likes to make things easier for coders from other languages. exit() is from C and die() is from perl.

Language Construct: include() and require()

Include and require are identical except that require() terminates the script if it fails while include() just displays an error. Both constructs includes and evaluates the specified file.
This construct uses your include path to include the script, unless prefixed with ./ or ../ then it looks in the current directory.

When a file is included in the main scope then its code is executed and variables are then avaiable in the rest of the main scope. If you use an include within a function or an object then its variables will only be avaiable within the functions scope, not the main scope.

You can use return tags in the included file, to ensure it was executed properly. The included file must contain valid PHP tags, otherwise the code will be displayed as raw data as its in html mode. You can include remote files but readfile() is much better for this.
vars.php

<?php
$color = 'green';
$fruit = 'apple';
?>

test.php

echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple

Language Construct: include_once() and require_once()

Identicle to include, exept if a file has allready be included once it will not be again. As the name says! only once!..
require_once() acts the same way, exept if the file that it is trying to include does not exist, then the whole script will be terminated.

Language Construct: return

returns data to its parent, for example.
If used within a function, it immediately ends execution of the current function and returns the data to the function call. If used within an eval() statement it will immediately end execution and return its value to the eval call.
If return was used in include or require then its data is passed back to the calling script and also terminates the included file.

Return is very useful, Its used a hell of a lot in functions and I will now use it in eval (if ever needed) and within included scripts!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis

2 Comments »

  • Much of its syntax is borrowed from C, specific features thrown in.
    Php Program Language

    Comment | October 7, 2008
  • Your right their mate “Language Construct: die()” outlines that many of this syntax is from C and Perl.
    Your website is very confusing but features some interesting reads!

    Comment | October 7, 2008

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS