How to call method in class variable? - php

Say I want to set a class variable equal to (to keep things simple):
public $variable = strtolower('Dog');
When I try to do anything like this, I get: syntax error, unexpected '(', expecting ',' or ';' ...
I'm sure this is an amateur mistake, but I've searched the forum and Google and cannot find an answer to this anywhere. How can I call a built-in (proper terminology?) method within a class variable?
Thank you.

You can initialize class properties to constant values, but not call a function. You can however do that within a constructor.
class Test {
public $var1 = 'Dog'; // <-- This is allowed
public $var2 = strtolower('Dog'); // <-- This is not allowed
public function __construct() {
$this->var2 = strtolower('Dog');
}
}
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.

Related

You can't run a function when defining an object property?

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.

Can I use dirname(__FILE__) as a part of a string?

I use dirname(__FILE__) in includes in php scripts but the other day I included it as part of a string and it caused an error. Any ideas?
THe line was
private $errorfile = dirname(__FILE__).'/../../../error_logs/error.log';
or
private $errorfile = '/../../../error_logs/error.log';
error_log($message,3, dirname(__FILE__).$this->errorfile);
and it caused an error such as
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home2/futsalti/public_html/_futsal-time-v4.9/public/scripts/php/databaseClass.php
PHP Parse error: syntax error, unexpected ';' in /home2/futsalti/public_html/_futsal-time-v4.9/public/scripts/php/databaseClass.php
EDIT:
Ok, just came to me... Maybe the question should be can I use dirname(__FILE__) inside a class?
Property default values must be a fixed constant value; you can't use dynamic values, variable, concatenated strings or function calls in the default value for a property.
You can use a constant, and as I noted earlier in a comment above, __DIR__ is a valid replacement for dirname(__FILE__).
Therefore, you could do this:
class myClass {
public $path = __DIR__;
}
That works, but you can't add anything else to it in the initial declaration, so although it gets closer, it doesn't really answer your question.
If it needs to be anything more than that, you'll need to define it in the code rather than the default value. I suggest declaring the variable as an empty string or null in the property declaration, and using your __construct() function to populate the value as required.
class myClass {
public $errorFile = null;
public function __construct() {
$this->errorFile = __DIR__ . ''/../../../error_logs/error.log';
}
}
Hope that helps.
Yeah, you can use dirname(__FILE__) inside a class, but not directly. Assign the path to the $errorfile in some function called before using that path.
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. source
You're trying to concatenate two strings together as the default value for a defined property within your class. You basically can't use any operations at all.
For example, this code would throw the error you're experiencing:
class Foo() {
private $bar = "string1"."string2";
}
This code would also throw the same error:
class Foo() {
private $bar = 1+1;
}
This code would not throw an error:
class Foo() {
private $bar = "string1string2";
}
A possible workaround to your problem might be creating a method which returns the error log.
class Foo() {
function getThing() {
return "string1"+"string2";
}
}
yes you can, you can use it anywhere but you just cant use it to set the default value of a property in a class. actually you can't with any function in general. if you would like to set that as a default value each time you instantiate the class, then place it in the constructor

Error while assigning a public propery

function CharField($len)
{
return "VARCHAR($len)";
}
class ArticleModel extends Model
{
public $name = CharField(100); // Error Here
}
When I assign a public property like this with a returned value from a function, it throws the error:
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in /var/www/test/db.php
What can the reason be?
You can only initialize properties with constants:
http://www.php.net/manual/en/language.oop5.properties.php
[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.
So indeed, initialize them in your constructor.
Initialize the value in your constructor
According to the manual you can only assign a constant value when instantiating a class property.

Zend and static class properties

I'm trying to assign a value to a static class property when defining it:
namespace Base;
abstract class Skeleton {
protected static $entityManager = \Zend_Registry::get("EntityManager");
...
}
When I try to execute this code I get this error:
Parse error: syntax error, unexpected '(', expecting ',' or ';' in /var/www/
somewhere/application/models/Base/Skeleton.php on line 6
If I just assign a simple string value to it:
protected static $entityManager = "string";
Everyting is fine. Am I doing something PHP can't handle? If so, how to solve this?
You can't put code that needs executing as a class variable, static or not.
Think about it, at which point does Zend_Registry::get("EntityManager") get executed, it can't be executed when the class is created because you have set it as static.
Even if it was not static, when does Zend_Registry::get("EntityManager") get run? When the object is instantiated or once? It needs to be put in a function inside the class.
Class properties may not depend on data that has to be evaluated at runtime:
[Class member variables] 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.
Add a setter and set the value during bootstrap.

Initialize class property with an anonymous function

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.

Categories