-
-
Save tzkmx/618593077ab2eccfdafa2155bafecdab to your computer and use it in GitHub Desktop.
PHP: One of ways to set/get a private/protected property. http://sandbox.onlinephpfunctions.com/code/d9caa381fe2a09473641e53b682194cd10b7096b
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
<?php | |
class Item | |
{ | |
private $cost = 100; | |
public function getTotal($discount = 7) { | |
return $this->cost *(100+$discount)/100; | |
} | |
} | |
class AccesserToPrivated | |
{ | |
public function getPrivate($obj, $attribute) { | |
$getter = function() use ($attribute) {return $this->$attribute;}; | |
return \Closure::bind($getter, $obj, get_class($obj)); | |
} | |
public function setPrivate($obj, $attribute) { | |
$setter = function($value) use ($attribute) {$this->$attribute = $value;}; | |
return \Closure::bind($setter, $obj, get_class($obj)); | |
} | |
} | |
$obj = new Item(); | |
$accesser = new AccesserToPrivated(); | |
$getCost = $accesser->getPrivate($obj, 'cost'); | |
$setCost = $accesser->setPrivate($obj, 'cost'); | |
echo 'Cost ' . $getCost() . ', total ' . $obj->getTotal() . PHP_EOL; | |
$setCost(1); //set new cost | |
echo 'Cost ' . $getCost() . ', total ' . $obj->getTotal() . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment