php.com code example
Example 1: php .com
<?php
$foo = "1";
$foo *= 2;
$foo = $foo * 1.3;
$foo = 5 * "10 Little Piggies";
$foo = 5 * "10 Small Pigs";
?>
Example 2: php .com
<?php
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public;
echo $obj->protected;
echo $obj->private;
$obj->printHello();
class MyClass2 extends MyClass
{
public $public = 'Public2';
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public;
echo $obj2->protected;
echo $obj2->private;
$obj2->printHello();
?>
Example 3: php .com
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
Example 4: php .com
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
Example 5: php .com
<?php
class SimpleClass
{
public $var = 'a default value';
public function displayVar() {
echo $this->var;
}
}
?>
Example 6: php .com
Regarding earlier note by @purkrt :
> I would like to stress out that the opening tag is "<?php[whitespace]", not just "<?php"
This is absolutely correct, but the wording may confuse some developers less familiar with the extent of the term "[whitespace]".
Whitespace, in this context, would be any character that generated vertical or horizontal space, including tabs ( \t ), newlines ( \n ), and carriage returns ( \r ), as well as a space character ( \s ). So reusing purkrt's example:
<?php echo "a"?>
would not work, as mentioned, but :
<?php echo "a"?>
will work, as well as :
<?php
echo "a"?>
and :
<?php echo "a"?>
I just wanted to clarify this to prevent anyone from misreading purkrt's note to mean that a the opening tag --even when being on its own line--required a space ( \s ) character. The following would work but is not at all necessary or how the earlier comment should be interpreted :
<?php
echo "a"?>
The end-of-line character is whitespace, so it is all that you would need.