Other than those described by http://php.net/manual/en/reserved.keywords.php, are there any method names I shouldn't use? For instance, can I make a method public function echo($x) and use it as $this->echo('Hello');?
EDIT> Evidently, I can't use echo because it is a language constructs, but could use min. Following doesn't result in an error.
<?php
class myClass {
public function min($x){echo(min($x));}
}
$obj=new myClass();
$obj->min(array(5,3,6,3));
?>
If you'd bothered actually trying:
php > class foo { function echo($bar) { print($bar); } }
PHP Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting identifier (T_STRING) in php shell code on line 1
You can't use language construct names in a classes regarding namespaces, while you can use built-in function names in namespace. A namespace in this case is a method of a class.
$foo = new Foo();
$foo->array_key_exists(); // Good
$foo->isset(); // Fatal error, since isset() a language construct
$foo->include(); // Also fatal error
The reason you don't get a fatal error when using min() is because its a built-in function.
Generally it's considered bad practice using built-in names in your own implementations because that might confuse another developers that will be reading your code in future.
Related
As of PHP 5.3, it is possible to use a variable as a class name, not only for object instantiation but even for static methods as well:
$className = 'My\Name\Spaced\Thing';
$thing = $className::foo('hello world');
However, if I try to use the return value of a function or method instead of an actual variable, I get an error:
function getClassName()
{
return 'My\Name\Spaced\Thing';
}
// Raises "syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)"
$thing = getClassName()::foo('hello world');
This, on the other hand, works just fine:
$className = getClassName();
$thing = $className::foo('hello world');
What gives? Did I just find a bug in PHP's (5.6) syntax processor?
I don't know if I'd call it a "bug," but it's certainly an idiosyncrasy of PHP prior to PHP 7. This, and a whole class of similar issues, was addressed by the Uniform Variable Syntax RFC.
The code in question...
class MyClass
{
public $template_default = dirname(__FILE__)."/default.tpl";
}
Why do I get the following error when I try to use the dirname() function when defining an object property?
Parse error: syntax error, unexpected '(', expecting ',' or ';' in ...
blah blah blah
I guess object properties are not like PHP variables.
That's right. From the docs:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Since dirname is a run-time function, it should be called in the constructor of the Object. So, set $template_default in the object constructor:
class MyClass {
public $template_default;
public function __construct(){
$this->template_default = dirname(__FILE__). "/default.tpl";
}
}
If you are using PHP 5.6, you can do the following:
class MyClass
{
public $template_default = __DIR__."/default.tpl";
}
PHP 5.6 allows simple scalar math and string concatenation in initialization now (docs), and __DIR__ is the same thing as dirname(__FILE__).
Otherwise, Drakes' answer is correct.
Why is not possible to initialize a property to a function when you declare the property in php? The following snippit results in a Parse error: syntax error, unexpected T_FUNCTION
<?php
class AssignAnonFunction {
private $someFunc = function() {
echo "Will Not work";
};
}
?>
Yet you can initialize a property to a string, number or other data types?
Edit:
But I can assign a function to a property in the __construct() method. The following does work:
<?php
class AssignAnonFunctionInConstructor {
private $someFunc;
public function __construct() {
$this->someFunc = function() {
echo "Does Work";
};
}
}
?>
Because it is not implemented in PHP.
http://www.php.net/manual/en/language.oop5.properties.php. Quote:
They (properties) are defined by using one of the
keywords public, protected, or
private, followed by a normal variable
declaration. This declaration may
include an initialization, but this
initialization must be a constant
value--that is, it must be able to be
evaluated at compile time and must not
depend on run-time information in
order to be evaluated.
You cannot initialize properties like this, functions are not constant values. Hence my original answer "it is not implemented".
Why is it not implemented? That I can only guess - it probably is quite a complex task and nobody has stepped up to implement it. And/or there may not be enough demand for a feature like that.
Closures do not exist in PHP until PHP 5.3 (the latest version). Make sure you have PHP 5.3 if you want to do this.
In earlier versions, you can sort of duplicate this functionality with the create_function() function, somewhat like this:
$someFunc = create_function($args,$code);
$someFunc();
Where $args is a string formatted like "$x,$y,$z" and $code is a string of your PHP code.
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!
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();
See Wikipedia on the scope resolution operator. Especially see the section on PHP and Hebrew.
You cannot use self this way : it can only be used in a static context (i.e. inside a static method) to point to the class -- and not its name.
If you are working with non-static methods (seems you are), you should use $this, instead of self.
Actually, before PHP 5.3, you cannot use a static method/data with a "dynamic" (i.e contained in a variable) class name -- see the examples on the page Static Keyword : they only work with PHP 5.3, for that kind of manipulation.
Which means a portion of code like this one :
class ClassA {
public static $data = 'glop';
}
$className = 'ClassA';
var_dump($className::$data);
Will not work with PHP < 5.3
I find this similar line works in my Laravel app:
$thing->all(new Account);
Try '$this' instead of self.
Self does work this way in PHP. PHP thinks it encounters an unknown constant, which it can't find, and then it assumes it's a string containing 'self'.
Edit: Can you post the class and the code where you instantiate the object?
Why is not possible to initialize a property to a function when you declare the property in php? The following snippit results in a Parse error: syntax error, unexpected T_FUNCTION
<?php
class AssignAnonFunction {
private $someFunc = function() {
echo "Will Not work";
};
}
?>
Yet you can initialize a property to a string, number or other data types?
Edit:
But I can assign a function to a property in the __construct() method. The following does work:
<?php
class AssignAnonFunctionInConstructor {
private $someFunc;
public function __construct() {
$this->someFunc = function() {
echo "Does Work";
};
}
}
?>
Because it is not implemented in PHP.
http://www.php.net/manual/en/language.oop5.properties.php. Quote:
They (properties) are defined by using one of the
keywords public, protected, or
private, followed by a normal variable
declaration. This declaration may
include an initialization, but this
initialization must be a constant
value--that is, it must be able to be
evaluated at compile time and must not
depend on run-time information in
order to be evaluated.
You cannot initialize properties like this, functions are not constant values. Hence my original answer "it is not implemented".
Why is it not implemented? That I can only guess - it probably is quite a complex task and nobody has stepped up to implement it. And/or there may not be enough demand for a feature like that.
Closures do not exist in PHP until PHP 5.3 (the latest version). Make sure you have PHP 5.3 if you want to do this.
In earlier versions, you can sort of duplicate this functionality with the create_function() function, somewhat like this:
$someFunc = create_function($args,$code);
$someFunc();
Where $args is a string formatted like "$x,$y,$z" and $code is a string of your PHP code.