Object
- Property
- Methods
- Visibility
- Static keyword
- Object Inheritance
- Abstract Class
- Interface
- Traits
- Object Array Interaction
Property
<?php
class Post
{
public $title;
public $text;
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
var_dump($post);
//=>
// object(Post)#1 (2) {
// ["title"] => string(17) "Lorem ipsum dolor"
// ["text"] => string(34) "Nunc accumsan in ipsum a mattis..."
var_dump($post->title); //=> string(17) "Lorem ipsum dolor"
Tips:
- The use of
$this
is required to access properties. - Old style constructors (name of the class) are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use
__construct()
in new code. - PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++.
Methods
<?php
class Post
{
public $title;
public $text;
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
public function toHMTL()
{
return "<div><h1>$this->title</h1><p>$this->text</p></div>";
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
var_dump($post->toHMTL());
//=> string(78) "<div><h1>Lorem ipsum dolor</h1><p>Nunc accumsan in ipsum a mattis...</p></div>"
Visibility
Visibility: public (+)
, protected (#)
, private (-)
<?php
class Post
{
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
var_dump($post->title); //=> string(17) "Lorem ipsum dolor"
$post->title = 'Dolor';
var_dump($post->title); //=> string(5) "Dolor"
<?php
class Post
{
private $title;
private $text;
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getText()
{
return $this->text;
}
public function setText($text)
{
$this->text = $text;
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
// $post->title; //=> Fatal error: Uncaught Error: Cannot access private property Post::$title
var_dump($post->getTitle()); //=> string(17) "Lorem ipsum dolor"
$post->setTitle('Dolor');
var_dump($post->getTitle()); //=> string(5) "Dolor"
<?php
class Post
{
private $title;
private $text;
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
var_dump($post->title); //=> string(17) "Lorem ipsum dolor"
$post->title = 'Dolor';
var_dump($post->title); //=> string(5) "Dolor"
Tips:
- Magic Method:
__construct()
,__destruct()
,__call()
,__callStatic()
,__get()
,__set()
,__isset()
,__unset()
,__sleep()
,__wakeup()
,__toString()
,__invoke()
,__set_state()
,__clone()
,__debugInfo()
Static keyword
<?php
class Point
{
public const SIZE = '2px';
public static $dimension = '2D';
public $x;
public $y;
public function __construct($x, $y)
{
$this->x = $x;
$this->y = $y;
}
public function __toString()
{
return "({$this->x},{$this->y})";
}
public static function kind()
{
return '[type: ' . self::$dimension . ', size:' . self::SIZE . ']';
}
public static function distance($a, $b)
{
$dx = $a->x - $b->x;
$dy = $a->y - $b->y;
return sqrt($dx ** 2 + $dy ** 2);
}
}
$p1 = new Point(5, 5);
$p2 = new Point(10, 10);
var_dump(Point::SIZE); //=> string(3) "2px"
var_dump(Point::$dimension); //=> string(2) "2D"
var_dump(Point::distance($p1, $p2)); //=> float(7.0710678118655)
var_dump('Point ' . Point::kind() . ' at ' . $p1);
//=> string(35) "Point [type: 2D, size:2px] at (5,5)"
Tips:
- Scope Resolution Operator (::): a token that allows access to static, constant, and overridden properties or methods of a class.
- As of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants declared without any explicit visibility keyword are defined as public.
Object Inheritance
<?php
class Person
{
public function __construct($name)
{
$this->name = $name;
}
public function hello()
{
return "Hello {$this->name}!";
}
}
class Student extends Person
{
public function __construct($name, $course)
{
parent::__construct($name);
$this->course = $course;
}
public function __toString()
{
return "Name: {$this->name}, Course: {$this->course}";
}
public function hello()
{
return parent::hello() . "(Course: {$this->course})";
}
}
$student = new Student('Fulano', 'TSI');
var_dump((string)$student); //=> string(25) "Name: Fulano, Course: TSI"
var_dump($student->hello()); //=> string(26) "Hello Fulano!(Course: TSI)"
Tips:
- If you want to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Abstract Class
<?php
abstract class Shape
{
protected $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public abstract function area();
public abstract function __toString();
}
class Square extends Shape
{
public function __construct($side)
{
$this->name = "square";
$this->side = $side;
}
public function area()
{
return $this->side ** 2;
}
public function __toString()
{
return "Shape {$this->name} (side: {$this->side}, area: {$this->area()})";
}
}
class Circle extends Shape
{
public function __construct($radius)
{
$this->name = "circle";
$this->radius = $radius;
}
public function area()
{
return M_PI * $this->radius ** 2;
}
public function __toString()
{
return "Shape {$this->name} (side: {$this->radius}, area: {$this->area()})";
}
}
class ShapeSet
{
private static $shapes = [];
public static function add($id, $shape)
{
self::$shapes[$id] = $shape;
}
public static function shapes()
{
return self::$shapes;
}
}
$c = new Circle(5);
ShapeSet::add(1, $c);
$s = new Square(10);
ShapeSet::add(2, $s);
print_r(ShapeSet::shapes());
//=>
// array(
// [1] => Circle Object(
// [name:protected] => circle
// [radius] => 5
// )[2] => Square Object(
// [name:protected] => square
// [side] => 10
// )
// )
Reference:
Interface
<?php
interface Calculator
{
public function addition($a, $b);
public function subtraction($a, $b);
}
interface Randomizer
{
public function random();
public function randomRange($min, $max);
}
class Util
{
public function addition($a, $b)
{
return $a + $b;
}
public function subtraction($a, $b)
{
return $a - $b;
}
public function multiplication($a, $b)
{
return $a * $b;
}
public function random()
{
return rand();
}
public function randomRange($min, $max)
{
return rand($min, $max);
}
}
$util = new Util();
var_dump($util->randomRange(1, 10)); //=> int(5)
var_dump($util->subtraction(100, 10)); //=> int(90)
Tips:
- It’s possible for interfaces to have constants.
Traits
<?php
trait CalculatorMixin
{
public function addition($a, $b)
{
return $a + $b;
}
public function subtraction($a, $b)
{
return $a - $b;
}
}
trait RandomizerMixin
{
public function random()
{
return rand();
}
public function randomRange($min, $max)
{
return rand($min, $max);
}
}
class Util
{
use CalculatorMixin, RandomizerMixin;
public function multiplication($a, $b)
{
return $a * $b;
}
}
$util = new Util();
var_dump($util->randomRange(1, 10)); //=> int(5)
var_dump($util->subtraction(100, 10)); //=> int(90)
Tips:
- As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
- Traits are a mechanism for code reuse in single inheritance languages such as PHP.
- Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.
- Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.
- Traits can define both static members and static methods.
- Traits can also define properties.
Object Array Interaction
<?php
class Address
{
function __construct($ip, $mask)
{
$this->ip = $ip;
$this->mask = $mask;
}
}
$ips = [
new Address("192.168.0.2", "255.255.255.0"),
new Address("192.168.0.10", "255.255.255.0"),
new Address("192.168.0.26", "255.255.255.0"),
new Address("192.168.0.30", "255.255.255.0")
];
foreach ($ips as $ip) {
print("{$ip->ip}/{$ip->mask}\n");
}
//=>
// 192.168.0.2/255.255.255.0
// 192.168.0.10/255.255.255.0
// 192.168.0.26/255.255.255.0