Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 773
Andreas Andreou Avatar asked Sep 19 '13 12:09

Andreas Andreou


1 Answers

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.

like image 174
Spudley Avatar answered Oct 16 '22 05:10

Spudley