Here's what I want to do:
public function all($model) {
$query = 'SELECT ' . implode(', ', $model::$fields) ....;
}
Called like this:
$thing->all(Account);
I get this error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /home/mark/public_html/*/account.php on line 15
When inspecting $model
with var_dump
it turns out its a string. In the the first example if I change $model
to Account
on the $query line it works fine.
How can a take a string and turn it back into a class?
Edit: Updated example and title to reflect the problem isn't with self
.
Solution: Since I'm not using PHP5.3, I had to resort to using eval() to get what I wanted. Thanks everybody!
SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.
class ¶ Basic class definitions begin with the keyword class , followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word.
you can use require_once() with exact path of that class after that you should use the object of the included class and function name for calling the function of outer class. Save this answer.
PHP: Class Constants When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).
Classes are not first-class citizens in PHP, as such they may not be stored in variables, passed as function arguments, or returned from functions.
However, PHP will let you simulate a first-class citizen by using a string containing the name of the class, in certain situations:
$class = "Account";
$instance = new $class(); // You can create instances
call_user_func(array($class, 'frobnicate')); // You can call static functions
That's about all in PHP < 5.3. However, with PHP 5.3, you can also:
$class::frobnicate(); // cleanly call static functions
$fields = $class::$fields; // access static variables
I have also experienced receiving such Fatal Error: Class 'MyClass' not found
when you're class has a specific namespace, then it's probably the namespacing. You need to also mention the namespace in your String variable.
$class = "App\MyClass"; // mention the namespace too
$instance = new $class();
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