In PHP5, what is the difference between using self and $this? When is each appropriate?

Use $this to refer to the current object.
Use self to refer to the current class.
In other words,
use $this->member for non-static members,
use self::$member for static members.

Use self to reference static class properties

<?php

class visitors
{
private static $visitors = 0;

function __construct()
{
self::$visitors++;
}

static function getVisitors()
{
return self::$visitors;
}

}

$visits = new visitors();
echo visitors::getVisitors()."
“;

$visits2 = new visitors();
echo visitors::getVisitors().”
“;

?>

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.