Skip to content

Instantly share code, notes, and snippets.

@githubjeka
Last active May 23, 2024 10:20

Revisions

  1. githubjeka revised this gist Jan 13, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion byClosure.php
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ class Item
    private $cost = 100;

    public function getTotal($discount = 7) {
    return $this->cost * $discount/(100+$discount);
    return $this->cost *(100+$discount)/100;
    }
    }

  2. githubjeka revised this gist Jan 13, 2016. No changes.
  3. githubjeka created this gist Jan 13, 2016.
    32 changes: 32 additions & 0 deletions byClosure.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    <?php
    class Item
    {
    private $cost = 100;

    public function getTotal($discount = 7) {
    return $this->cost * $discount/(100+$discount);
    }
    }

    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;