Skip to content

Instantly share code, notes, and snippets.

@githubjeka
Last active May 23, 2024 10:20
Show Gist options
  • Save githubjeka/153e5a0f6d15cf20512e to your computer and use it in GitHub Desktop.
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
<?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;
@Nguimjeu
Copy link

Nguimjeu commented May 3, 2022

Much appreciated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment