Last active
May 23, 2024 10:20
-
-
Save githubjeka/153e5a0f6d15cf20512e 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 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
Much appreciated