Across an Instance

Here’s the quick PHP tip of the day: class methods can access the protected (of any shared ancestors) and private (of the same type) members of any instance, not only their own instance. That may sound confusing, but it’s really not so much.

Maybe some example code will explain it better. Let’s say I have a class that’s a counter, just wrapping an integer.


<?php
class Counter
{
    protected $count = 0;
    
    public function increment()
    {
        $this->count++;
    }

    public function getCount()
    {
        return $this->count;
    }
}

?>

And now, for some reason, I want to add two counters together. I add a method to Counter named add() that accepts another instance of Counter. But rather than calling increment() $count times, I can simply write:


    public function add(Counter $c)
    {
        $this->count += $c->count;
    }

Blindingly simple, really, but something I often forget about.

Leave a Reply