Skip to content

Instantly share code, notes, and snippets.

@consatan
Forked from githubjeka/byClosure.php
Created August 3, 2016 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save consatan/b93de6517edfc573d83e5908cd4b9bda to your computer and use it in GitHub Desktop.
Save consatan/b93de6517edfc573d83e5908cd4b9bda 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment