Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP 5.4: Accessor with trait example
<?php
// Example code how to eliminate getter and setter methods
// with traits introduced from PHP 5.4
trait Accessors {
public function __get($name) {
if ($this->r_property[$name])
return $this->$name;
else
trigger_error("Access to read protected property");
}
public function __set($name, $value) {
if ($this->w_property[$name])
$this->$name = $value;
else
trigger_error("Access to write protected property");
}
}
class OrderLine {
use Accessors;
private $r_property = array('price'=>1, 'amount'=>1);
private $w_property = array('price'=>0, 'amount'=>1);
protected $price;
private $amount;
private $tax = 1.15; // property without getter/setter
public function getTotal() {
return $this->price * $this->amount * $this->tax;
}
}
$line = new OrderLine;
$line->price = 20;
$line->amount = 3;
echo "Total cost: ".$line->getTotal();
?>
@kassner

This comment has been minimized.

Show comment
Hide comment
@kassner

kassner Nov 20, 2011

If you are not using getter/setter methods, I think you are killing all visibility introduced in PHP 5.

kassner commented Nov 20, 2011

If you are not using getter/setter methods, I think you are killing all visibility introduced in PHP 5.

@yohgaki

This comment has been minimized.

Show comment
Hide comment
@yohgaki

yohgaki Nov 20, 2011

You can control visibility and accessibility via $r_property and $w_property.
This code is example to show how we can avoid getter and setter methods with trait.

Owner

yohgaki commented Nov 20, 2011

You can control visibility and accessibility via $r_property and $w_property.
This code is example to show how we can avoid getter and setter methods with trait.

@kassner

This comment has been minimized.

Show comment
Hide comment
@kassner

kassner Nov 20, 2011

Oh, yes, we will spent less time writing getters and setters, but we will lose visibility in our IDE. This doesn't sounds useful. However, it is a good traits usage example.

kassner commented Nov 20, 2011

Oh, yes, we will spent less time writing getters and setters, but we will lose visibility in our IDE. This doesn't sounds useful. However, it is a good traits usage example.

@anyt

This comment has been minimized.

Show comment
Hide comment
@anyt

anyt Dec 29, 2013

For IDE visibility we can use PhpDoc

anyt commented Dec 29, 2013

For IDE visibility we can use PhpDoc

@jon49

This comment has been minimized.

Show comment
Hide comment
@jon49

jon49 Oct 16, 2014

How would you do inheritance with this (assuming you are using Accessor in both the parent and the child)? Or is it even possible?

jon49 commented Oct 16, 2014

How would you do inheritance with this (assuming you are using Accessor in both the parent and the child)? Or is it even possible?

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