There's a few key assumptions your'e bringing from ruby that don't translate well into PHP.
The correct way to declare and use object properties (equivalent to Ruby's instance variables) in PHP is
class Foo
{
//accesible from inside this objects of this class,
//objects that have this class as an ancestor, and from
//outside the object
//var $bar; is equivalent. "var" is PHP 4 syntax,
//when everything was public
public $bar;
//accesible from inside this objects of this class,
//objects that have this class as an ancestor
protected $baz;
//accesible from inside this objects only
private $fiz;
protected function example()
{
echo $this->bar . "\n";
echo $this->baz . "\n";
echo $this->fiz . "\n";
}
}
PHP's OO syntax is based on the Java/C# view of the world. However, because every PHP page/script/program starts off in the global score, the $this
pseudo reference to the local object is needed. Without it, you'd create a large degree of ambiguity around situations like this
//In main.php
$foo = "bar";
include('example.php');
//in example.php
class Example
{
public $foo="baz";
public function scopeIsHardLetsGoShopping()
{
global $foo;
echo $foo;
}
}
So, in the method should the $foo referenced be the object variable, or the global variable? If you say it should be the object variable, how do you access the global foo from a method? If you say it should be the global variable how do you access the local property after declaring a variable with the same name global?
Ruby and python gave scoping some thoughts at the onset of the language, so these problems can be avoided. PHP started as a quick way to hack in some c-code to process forms and output HTML. Because PHP makes reasonable efforts to be backwards compatible, you end up with quirky work arounds like $this.
Coming form Ruby it seems a little verbose, but it's a fundamental part of PHP.