Skip to content

Instantly share code, notes, and snippets.

@Y0lan
Created June 26, 2019 22:05
Show Gist options
  • Select an option

  • Save Y0lan/50735d7bf4dbe354a9c1a7652117ed81 to your computer and use it in GitHub Desktop.

Select an option

Save Y0lan/50735d7bf4dbe354a9c1a7652117ed81 to your computer and use it in GitHub Desktop.
repeat get set in function
<?php
// create a class User with :
// name
// age
// create a class Customers extended from User
// create a method pay() that simulate a customers paying
Class User {
protected $name;
protected $age;
public function __construct($name, $age){
$this->age = $age;
$this->name = $name;
}
public function __get($property){
if(!property_exists($this, $property)){
echo $property . " does not exist in " . $this;
return NULL;
}
return $this->$property;
}
public function __set($property, $value){
if(gettype($value) != gettype($property)){
echo "can not affect something of type " . gettype($value) . " into " . $property . " of type "
. gettype($property);
return NULL;
}
if(!property_exists($this, $property)){
echo $property . " does not exist in " . $this;
return NULL;
}
$this->$property = $value;
}
}
Class Customers extends User{
private $balance;
public function __construct($name, $age, $balance)
{
parent::__construct($name, $age);
$this->balance = $balance;
}
public function __get($property){
if(!property_exists($this, $property)){
echo $property . " does not exist in " . $this;
return NULL;
}
return $this->$property;
}
public function __set($property, $value){
if(gettype($value) != gettype($property)){
echo "can not affect something of type " . gettype($value) . " into " . $property . " of type "
. gettype($property);
return NULL;
}
if(!property_exists($this, $property)){
echo $property . " does not exist in " . $this;
return NULL;
}
$this->$property = $value;
}
public function pay($value){
if($this->balance - abs($value) < 0){
echo "Insufficient Balance";
return NULL;
}
if(!is_numeric($value)){
echo $value . "is not a number";
return NULL;
}
$this->balance = $this->balance - $value;
echo $this->name . " paid $ " . $value . "<br>";
echo $this->name . " have a balance of $ " . $this->balance . "<br>";
}
}
$customer = new Customers("Yolan", 22, 10);
$customer->pay(4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment