05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

assigns $b the integer value of $a; $a remains the string "5". To cast the value of the<br />

variable itself, you must assign the result of a cast back into the variable:<br />

$a = "5"<br />

$a = (int) $a; // now $a holds an integer<br />

Not every cast is useful: casting an array to a numeric type gives 1, and casting an<br />

array to a string gives "Array" (seeing this in your output is a sure sign that you’ve<br />

printed a variable that contains an array).<br />

Casting an object to an array builds an array of the properties, mapping property<br />

names to values:<br />

class Person {<br />

var $name = "Fred";<br />

var $age = 35;<br />

}<br />

$o = new Person;<br />

$a = (array) $o;<br />

print_r($a);<br />

Array<br />

(<br />

[name] => Fred<br />

[age] => 35<br />

)<br />

You can cast an array to an object to build an object whose properties correspond to<br />

the array’s keys and values. For example:<br />

$a = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');<br />

$o = (object) $a;<br />

echo $o->name;<br />

Fred<br />

Keys that aren’t valid identifiers, and thus are invalid property names, are inaccessible<br />

but are restored when the object is cast back to an array.<br />

Assignment Operators<br />

Assignment operators store or update values in variables. The autoincrement and<br />

autodecrement operators we saw earlier are highly specialized assignment operators—here<br />

we see the more general forms. The basic assignment operator is =, but<br />

we’ll also see combinations of assignment and binary operations, such as += and &=.<br />

Assignment<br />

The basic assignment operator (=) assigns a value to a variable. The lefthand operand<br />

is always a variable. The righthand operand can be any expression—any simple<br />

literal, variable, or complex expression. The righthand operand’s value is stored in<br />

the variable named by the lefthand operand.<br />

44 | Chapter 2: Language Basics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!