|
Comments are supported in the normal C/C++ and Java style:
|
PHP supports the following data types:
|
Example:
|
|
|
Variable Scope:
The single scope of most variables in PHP spans the entire file plus any
included files. For instance if you define $a = 1;
then a will be available within any included files.
Local Variables: Any variable used inside a user-defined function, however, has its scope limited to the local function. In addition, global variables are not available inside local functions unless declared with the global keyword:
$a = 1; |
||
Some basic PHP statements include:
|
Examples:
echo "Hello World."; |
|
|
PHP expressions can include: $a = $b = 5; //The assignment statement $b = $a++; //Post-increment a $b = ++$a; //Pre-increment a $x = $bool ? $a : $b; //Ternery conditional The last expression evaluates to if ($bool) $x = $a else $x = $b. |
|
Operators:
|
|
Maths:
|
|
Strings can be specified in 3 ways: single quotes, double quotes, or heredoc.
Strings in single quotes do not expand variables or escape sequences except
for single quotes: echo 'I\'ll be back.';. echo 'The newline \n will not expand'; $a = 'Gators'; echo 'The value of $a is ' . $a; -> The value of $a is Gators If a string is enclosed in double quotes, escapes such as may be used and variables are expanded: echo "Go $a"; -> Go Gators echo "{$a}bait!"; -> Gatorbait! Heredoc syntax: Starts with <<< followed by an identifier. Ends with the identifier repeated at the start of a line. echo <<<ABC This is an example of a string in the heredoc syntax. Always use braces around arrays when inside of strings: The 3rd person's name is {$people['names'][3]} ABC; |
String Operators: Concatenation is done with the '.' operator. Converting to numbers: $x = 1 + "10.5"; //$x=11.5, float $x = 4 - "3"; //$x=1, int You can convert to a string with the (string) cast or the strval function Booleans are converted to strings as "1" or "" (empty string). Values are also converted to strings when a string is needed, such as when using the echo or print functions. | |
|
String Functions:
|
||
|
Array Operators:
|
|
Array Functions:
|
|
Examples:
if ($a > $b) echo "a is greater than b"; |
|
Examples:
for ($j = 0; $j < 10; $j++) { |
|
PHP supports OOP and classes. A class is a collection of variables and
functions working with these variables. Classes are defined similarly to
Java except that "" is used instead of
"" when referring to functions and elements of
a class. You can NOT break up a class definition into multiple files
or multiple PHP blocks.
|
Example Class: class Rectangle { //Define variables width and height var $width, $height; //Constructor function Rectangle($width = 0, $height = 0) { $this->width = $width; $this->height = $height; } //functions function setWidth($width) { $this->width = $width; } function setHeight($height) { $this->height = $height; } function getArea() { return $this->width * $this->height; } } $arect = new Rectangle(); //create a new Rectangle with dimensions 0x0. $arect->setWidth(4); $arect->setHeight(6); echo $arect->getArea(); -> 24 $rect2 = new Rectangle(7,3); //new Rectangle with dimensions 7x3. Extended Class: class RectWithPerimeter extends Rectangle { //add new functions function getPerimeter() { return 2*$this->height + 2*$this->width; } function setDims($width, $height) { //use the parent keyword to call methods from Rectangle parent::setWidth($width); parent::setHeight($height); } } $arect = new RectWithPerimeter(6,5); //Uses the constructor from Rectangle because no new constructor is provided to override it. echo $arect->getArea(); //Uses the getArea function from Rectangle and prints 30. echo $arect->getPerimeter(); //Uses getPerimeter from RectWithPerimeter and prints 22. $arect->setDims(4,9); //Use setDims to change the dimensions. |
PHP allows for reading/writing to files on the server that have correct
permissions.
|
|
Examples: $file = fopen("data/teams.txt","r"); while (!feof($file)) { $team = fgets($file); echo $team; } fclose($file); $imgf = fopen("../img/football.jpg","rb"); $image = ""; while (!feof($imgf)) { $image .= fread($imgf,1024); } fclose($imgf); $player = serialize(new Player("J.J. Redick", "Duke", 4)); $file = fopen("data/players.txt", "a"); if (flock($fp, LOCK_EX)) { fwrite($file, $player); flock($file, LOCK_UN); } else echo "Couldn't lock the file!"; fclose($file); $html = file_get_contents('http://www.example.com/'); |
|
When a form is submitted to a PHP script, the information from that form
is automatically available to the script via several methods. First, you
will want to set a form's action="script.php" and choose which method to use,
"get" or "post". Get appends the arguments to the URL, while Post does not.
PHP can then access the information from the form by the arrays
and ,
depending on which method you used. The syntax is
$var = $_POST['element_name'];, where element_name is the name assigned
to a particular form element in the HTML code. If you do not care which
method the form used, you can use the
array, which contains the contents of $_GET, $_POST, and $_COOKIE.
bool isset(mixed var): isset can be used to check whether a form has been submitted. It can also be used on any variable, returning TRUE if the variable exists. if (isset($_POST['name'])) ... Image Submit variables: When using an image to submit a form instead of a standard submit button (), the form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. Reading into arrays: By using [] or [key] within the name of the form element in the HTML, you can read the form information into arrays, i.e. $_POST['personal']['name'] or $_POST['beer'][0]. See the example to the right. If I had used personal[] for both Name and E-mail, then those values could be accessed by $_POST['personal'][0] and $_POST['personal'][1] respectively. |
Examples: script.php: echo "Your name is " . $_POST['name']; $email = $_POST['email']; echo '<a href="mailto:' . $email . '">Send e-mail</a> A more complex example: if (isset($_POST['is_submitted']) && $_POST['is_submitted'] == 'submitted') { print_r($_POST); echo '<a href="'. $_SERVER['PHP_SELF'] .'">Try again</a>'; } else { echo $_SERVER['PHP_SELF']; } |
|
Here is the code for Guess My Number in PHP, a program that generates a
random number between 1 and 100 and asks the user to guess it. It will tell
the user if the number is higher or lower after each guess and keep track of
the number of guesses. This is just one way to write it in PHP.
$b = $_POST['b']; $x = $_POST['x']; $out = $_POST['out']; if ($b == 0) { $x = mt_rand(1,100); $out = ""; } |