Reputation: 33
trying to learn php and caught on another snagg
Ok this is what they are saying on php.net below about the ::
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
When referencing these items from outside the class definition, use the name of the class.
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE;
echo MyClass::CONST_VALUE;
?>
now back to the above code
$classname = 'MyClass';
THAT IS A VARIABLE ! BEING GIVEN A 'STRING' VALUE OF 'MyClass'!
echo $classname::CONST_VALUE;
SO HOW IS THIS LINE EVEN POSSIBLE! IT HAS NOTHING TO DO WITH THAT CLASS!
THAT IS BASICALLY A SIMPLE VARIABLE WITH A STRING VARIABLE! SO HOW DOES IT MAGICALLY GET THE POWER TO ACCESS THAT CLASS CONSTANT WITH ::? ONLY THING SIMILAR I SEE IS THE STRING 'MyClass' buts in theory has no power to let that happen its just a string.
can someone explain because im having 100 snags a day im starting to think php was just made up as they went along its too many contradictory things in it.
Upvotes: 0
Views: 122
Reputation: 333
In this case these two lines are basically the same.
echo $classname::CONST_VALUE;
echo MyClass::CONST_VALUE;
PHP tries to "cast" the string "MyClass"
to a Class. If the class exists everything works like a charm.
Other example could be:
$instance = new $classname;
where $instance
is a valid instance of MyClass
.
In other words you can replace class name with its string representation.
Upvotes: 1