php basics code example
Example 1: how to use php
// Firstly you must have PHP installed & running a web server
// This could be Apache, Nginx, etc...
// Or for quick testing purposes and for the purpose
// of this example, you could run
// PHP's own dev server from a shell
php -S 127.0.0.1:8080 -t your-web-directory-location
// This will start a web server on localhost port 8080
// The -t switch sets the document root, this is where your
// home page, typically index.php will be situated
// very basic index.php example
<?php
echo "Hello, world!";
?>
// You can now go to a browser and enter 127.0.0.1:8080
// You will presented with your simple web page
// Hello, world!
Example 2: php
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>
Example 3: php
<?php
class Connection
{
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
}?>
Example 4: ?? php
?: // !empty()
?? // isset()
Example 5: php
PHP is a general-purpose scripting language especially suited to
web development.
It was originally created by Danish-Canadian programmer
Rasmus Lerdorf in 1994;
the PHP reference implementation is now produced by The PHP Group
Implementation language: C (primarily; some components C++)
Example 6: basic php
<?php
// This is a comment
echo 'Hello, World!';
// And this outputs Hello, World!
?>