PHP

From Code Self Study Wiki
Jump to: navigation, search

PHP is the most popular web server (back-end) programming language. (measured by number of websites using it)

Notes on PHP:

PHP 5.4 Development Server

Turn on a server on development machine:

$ php -S localhost:8888 -t public/

To run the server in the current directory:

$ php -S localhost:8888

Then go to localhost:8888 in the browser to view the site.

OOP

Example:

<?php
 
class Person
{
    private $name;
 
    public function setName($name)
    {
        $this->name = $name;
    }
 
    public function getName()
    {
        return $this->name;
    }
 
    public function writeCode($code)
    {
        return "<pre><code>$code</code></pre>";
    }
}
 
$person = new Person();
$person->setName('Josh');
 
echo $person->getName();
echo $person->writeCode('[(x, y) for x in range(10) for y in range(10) if x != y]');
 
echo '<pre>';
var_dump($person);
echo '</pre>';

Another example:

<?php
 
class Person
{
 
    function __construct($name)
    {
        $this->name = $name;
    }
 
    function __destruct()
    {
        echo 'Object destroyed';
    }
 
    public function getName()
    {
        return $this->name;
    }
 
    public function speak($words)
    {
        return $words;
    }
}
 
$person = new Person('Josh');
 
echo $person->getName() . '<br>';
echo $person->speak('Saluton, Mondo!');
 
echo '<pre>';
var_dump($person);
echo '</pre>';

Static

Adapted from the PHP docs:

<?php
class Foo
{
    public static $my_static = 'foo';
 
    public function staticValue() {
        return self::$my_static;
    }
}
 
class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}
 
// The following, except #3, will all print `foo` to the page
print '<pre>';
print '1. ' . Foo::$my_static . "\n";
 
$foo = new Foo();
print '2. ' . $foo->staticValue() . "\n";
 
// #3 doesn't work
// print '3. ' . $foo->my_static . "\n";      // Undefined "Property" my_static 
 
print '4. ' . $foo::$my_static . "\n";
 
$classname = 'Foo';
print '5. ' . $classname::$my_static . "\n"; // As of PHP 5.3.0
 
print '6. ' . Bar::$my_static . "\n";
$bar = new Bar();
print '7. ' . $bar->fooStatic() . "\n";
print '</pre>';

See Also

To Research