Last active
June 13, 2017 19:37
-
-
Save antoniojps/3d3774dfc60e62169e250ea5157ee4f3 to your computer and use it in GitHub Desktop.
PHP OOP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OBJECT ORIENTED PROGRAMMING PHP | |
// Constructor de objecto = class | |
// Propriedades e Metodos (funcoes) | |
class Person{ | |
public $name; | |
public $email; | |
} | |
// Access modifiers: | |
// Public : qualquer lado | |
// Private: dentro da classe | |
// Protected: dentro da classe e extends | |
// Instanciar (criar objeto) | |
$person1 = new Person; | |
// Aceder a propriedades (SEM $ !!!) | |
$person1->name | |
// Construtor de funçoes, corrido quando instanciamos objeto | |
// $this refere-se à classe | |
// Magic method sao os que começam com __x() | |
class Person { | |
private $name; | |
private $email; | |
public function __construct($name,$email){ | |
$this-$name = $name; | |
$this->email = $email; | |
echo __CLASS__.'criado'; // 'Person criado', da o nome da classe | |
} | |
public function __destruct(){ | |
echo __CLASS__.'destruido'; // Destroi classe | |
} | |
public function getName(){ | |
return $this->name; | |
} | |
} | |
$person1 = new Person('Antonio Sensual','[email protected]'); | |
echo $person1->getName(); // 'Antonio Sensual' | |
// EXTENDS | |
// Extende os metodos e propriedades para outra classe | |
// Static metodos e funcoes sao "getted" com :: | |
class Customer extends Person{ | |
private $balance; | |
public function __construct($name,$email,$balance){ | |
parent::__construct($name,$email,$balance); // adicionar parametro a class parente | |
$this->balance = $balance; | |
echo 'A new '.__CLASS__.'has been created'; // A new customer has been created | |
} | |
} | |
// STATIC PROPS E METHODS :: | |
// Podemos aceder sem instanciar objeto, sao estaticos | |
class Person{ | |
public static $idadeMin = 18; | |
public static function obterIdadeMin(){ | |
return self::$idadeMin; | |
} | |
} | |
echo Person::$idadeMin; // 18 | |
echo Person:obterIdadeMin(); // 18 | |
// NAMESPACES | |
// É o espaço do nome onde esta o ficheiro, imaginemos scopes | |
// GLOBAL/DENTRO/AINDAMAISDENTRO | |
namespace Antonio\Bom; | |
class Antonio { | |
public function __construct(){ | |
echo 'O Antonio é bom'; | |
$datetime = new \Date(); // Usar um \ antes da classe se tiver no scope global | |
} | |
} | |
// Depois noutro ficheiro | |
use Antonio\Bom as Antonio; | |
new Antonio(); // 'O Antonio é muita bom' echo | |
// Podemos usar os namespaces dentro de namespaces, se por exemplo tivermos no namespace \Antonio depois poderiamos fazer apenas new Bom(); | |
// PODEM SER NESTED | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment