I have been stepping up my PHP game lately. Coming from JavaScript, I've found the object model to be a little simpler to understand.
I've run into a few quirks that I wanted some clarifying on that I can't seem to find in the documentation.
When defining classes in PHP, you can define properties like so:
class myClass {
public $myProp = "myProp";
static $anotherProp = "anotherProp";
}
With the public variable of $myProp
we can access it using (assuming myClass
is referenced in a variable called $myClass
) $myClass->myProp
without the use of the dollar sign.
We can only access static variables using ::
. So, we can access the static variable like $myClass::$anotherProp
with a dollar sign.
Question is, why do we have to use dollar sign with ::
and not ->
??
EDIT
This is code I would assume would work (and does):
class SethensClass {
static public $SethensProp = "This is my prop!";
}
$myClass = new SethensClass;
echo $myClass::$SethensProp;
The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using the $ symbol before the $x value. These are called variable variables in PHP.
Nope. Variables in PHP must start with $ . The other approach is to use constants. Constants aren't "another approach" to variables if you need to modify the contents of the variable.
In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class. That's why it is sometimes referred as instance variable.
The @ symbol is the error control operator ("silence" or "shut-up" operator). It makes PHP suppress any error messages (notice, warning, fatal, etc) generated by the associated expression. It works just like a unary operator, for example, it has a precedence and associativity.
A class constant is accessed with the ::
scope operator, and no dollar sign, so the $
is needed there to differentiate between static class properties and class constants.
class myClass {
public static $staticProp = "static property";
const CLASS_CONSTANT = 'a constant';
}
echo myClass::CLASS_CONSTANT;
echo myClass::$staticProp;
So to access a variable, the $
is necessary. But the $
cannot be placed at the beginning of the class name like $myClass::staticProp
because then the class name could not be identified by the parser, since it is also possible to use a variable as the class name. It must therefore be attached to the property.
$myClass = "SomeClassName";
// This attempts to access a constant called staticProp
// in a class called "SomeClassName"
echo $myClass::staticProp;
// Really, we need
echo myClass::$staticProp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With