Warning: Undefined array key 0 in /home/mawagner/public_html/wp-content/plugins/if-modified-since-header/if-modified-since-http-header.php on line 47 Warning: Attempt to read property "comment_date" on null in /home/mawagner/public_html/wp-content/plugins/if-modified-since-header/if-modified-since-http-header.php on line 47 Warning: Undefined array key 0 in /home/mawagner/public_html/wp-content/plugins/if-modified-since-header/if-modified-since-http-header.php on line 48 Warning: Attempt to read property "comment_date" on null in /home/mawagner/public_html/wp-content/plugins/if-modified-since-header/if-modified-since-http-header.php on line 48 Across an Instance - Everybody Dance Now

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

Warning: Undefined variable $user_ID in /home/mawagner/public_html/wp-content/themes/Elite/comments.php on line 80