From the udemy course Object Oriented PHP & MVC from Brad Traversy
<?php
class User {
public $name;
public $age;
public static $minPassLength = 6;
public static function validatePass($pass) {
// We use self:: because $minPassLength is static
if(strlen($pass) >= self::$minPassLength) {
return true;
} else {
return false;
}
}
}
$password = 'hello1';
if(User::validatePass($password)) {
echo 'Password valid';
} else {
echo 'Password NOT valid';
}
<?php
class User {
protected $name;
protected $age;
public function __construct($name, $age) {
$this -> name = $name;
$this -> age = $age;
}
}
class Customer extends User {
private $balance;
public function __construct($name, $age, $balance) {
parent::__construct($name, $age);
$this -> balance = $balance;
}
public function pay($amounth) {
return $this -> name . ' paid $' . $amounth;
}
public function getBalance() {
return $this -> balance;
}
}
$customer1 = new Customer('John', 41, 500);
echo $customer1 ->pay(100) . ' and has left ' . $customer1 -> getBalance();
<?php
class User {
private $name;
private $age;
public function __construct($name, $age) {
$this -> name = $name;
$this -> age = $age;
}
public function getName() {
return $this -> name;
}
public function setName($name) {
$this -> name = $name;
}
// __get MAGIC METHOD
public function __get($property) {
if(property_exists($this, $property)) {
return $this -> $property;
}
}
// __set MAGIC METHOD
public function __set($property, $value) {
if(property_exists($this, $property)) {
return $this -> $property = $value;
}
return $this;
}
}
$user1 = new User('John', 40);
//echo $user1 -> setName('Jeff');
//echo $user1 -> getName();
$user1 -> __set('age', 41);
echo $user1 -> __get('name') . '<br>';
echo $user1 -> __get('age') . '<br>';
<?php
class User {
public $name;
public $age;
// Runs when an object is created
public function __construct($name, $age) {
echo 'Class ' . __CLASS__ . ' is instanciated<br>';
$this -> name = $name;
$this -> age = $age;
}
public function sayHello() {
return $this -> name . ' says hello!';
}
// Called when no other references to a certain object
// Used for cleanup, closing conntections etc
public function __destruct() {
echo 'destructor ran....';
}
}
$user1 = new User('Brad', 36);
echo $user1 -> name . '<br>';
echo $user1 -> age . '<br>';
echo $user1 -> sayHello() . '<br>';
$user2 = new User('Jeff', 45);
echo $user2 -> name . ' is ' . $user2 -> age . ' years old<br>';
<?php
// Define a class
class User {
// Properties (attributes)
public $name = 'Brad';
// Methods (functions)
public function sayHello() {
return $this->name . ' Says Hello';
}
}
// Instatiate a user object from the user class
$user1 = new User();
$user1 -> name = 'Brad';
echo $user1 -> name;
echo '<br>';
echo $user1 -> sayHello();
echo '<br>';
// Create new user
$user2 = new User();
$user2 -> name = 'Jeff';
echo $user2 -> name;
echo '<br>';
echo $user2 -> sayHello();