New to php. I am writing a class and was wondering why some variable $variable
does not need a $
when calling $this->variable
?
In Object Oriented Programming when you declare variables like so
public $variable;
these are no more variables but are the properties of the object of the class. So when we call these properties we reference these through $this->property
Which means that we are calling the property of the present object. $this
refers to the instance of the present class. Whenever you would call properties and methods within class you have to use $this->property-or-method
.
Because that variable is inside a larger variable called an Object
and the object knows how to access it's inner variables / functions. Like a smart-variable.
Objects can be used to group data or similar functions (called method's when they are inside of an object)
For data/values, you could also use an array. It's common to see data stored in objects as well.
But you wouldn't store functions in an array. In PHP that's a no-go, but in JavaScript that's all good.
Back to objects, functions stored in objects are called methods. Objects can contain methods or properties.
Object Method / Function Example from: http://php.net/manual/en/language.types.object.php
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
// also valid $bar::do_foo();
?>
Object Property / Variable Example From: http://php.net/manual/en/language.oop5.properties.php
<?php
class SimpleClass
{
// valid as of PHP 5.6.0:
public $var1 = 'hello ' . 'world';
// valid as of PHP 5.3.0:
public $var2 = <<<EOD
hello world
EOD;
// valid as of PHP 5.6.0:
public $var3 = 1+2;
// invalid property declarations:
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = array(true, false);
// valid as of PHP 5.3.0:
public $var8 = <<<'EOD'
hello world
EOD;
}
?>
It is not the variable. It means object oriented. It's a reference to the current object, it's most commonly used in object oriented code.
Example:
<?php
class Person {
public $name;
function __construct( $name ) {
$this->name = $name;
}
};
$jack = new Person('Jack');
echo $jack->name;
This stores the 'Jack' string as a property of the object created.