Skip to content

Instantly share code, notes, and snippets.

@MontealegreLuis
Created July 24, 2014 03:22
Show Gist options
  • Save MontealegreLuis/bedfa417cf0c188ae9d1 to your computer and use it in GitHub Desktop.
Save MontealegreLuis/bedfa417cf0c188ae9d1 to your computer and use it in GitHub Desktop.
OOP visibility and type hinting examples
<?php
class Autoloader
{
/**
* @param string $className
*/
public function autoload($className)
{
require str_replace('\\', '/', $className) . '.php';
}
public function register()
{
spl_autoload_register([$this, 'autoload']);
}
}
<?php
namespace Company;
class Employee extends Person
{
/** @type Money */
protected $salary;
/**
* @param string $name
* @param integer $age
* @param Money $salary
*/
public function __construct($name, $age, Money $salary)
{
parent::__construct($name, $age);
$this->salary = $salary;
}
/**
* @param string $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
}
<?php
require 'Autoloader.php';
use Company\Person;
use Company\Employee;
use Company\Money;
$autoloader = new Autoloader();
$autoloader->register();
$luis = new Person('Luis', 34);
$luis->name;
echo $luis->getAge();
$enrique = new Employee('Enrique', 'Cincuenta', new Money(10000, 'MXN'));
$enrique->setLastName('Hernández');
echo $enrique->getAge();
$gregorio = new Employee('Gregorio', 20, new Money(20000, 'USD'));
echo $gregorio->getAge();
<?php
namespace Company;
class Money implements CastsToJson
{
use ProvidesJsonEncoding;
/** @type integer */
protected $amount;
/** @type string */
protected $currency;
/**
* @param integer $amount
* @param string $currency
*/
public function __construct($amount, $currency)
{
$this->amount = $amount;
$this->currency = $currency;
}
}
<?php
namespace Company;
class Person
{
/** @type string */
public $name;
/** @type string */
protected $lastName;
/** @type integer */
private $age;
/**
* @param string $name
* @param integer $age
*/
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
/**
* @return integer
*/
public function getAge()
{
return $this->age;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment