Can I use dirname(__FILE__) as a part of a string? - 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?

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

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.

How to access constants none static way

if a constant is defined in class like this:
class Example
{
const MIN_VALUE = 0.0; // RIGHT - Works INSIDE of a class definition.
}
it is possible to access the constant like this:
Example::MIN_VALUE
but if you do this:
class Sample {
protected $example;
public function __construct(Example $example){
$this->example = $example;
}
public function dummyAccessToExampleConstant(){
//doesn't work -> syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
if($this->example::MIN_VALUE === 0.0){
}
//this works
$tmpExample = $this->example;
if($tmpExample::MIN_VALUE === 1){
}
}
}
Can somebody explain me the reason of this behaviour ?
Is there a good reason or is it just a language construct that prevents the access with "::"
Is there a way how to access a constant with "$this"
This is one of those unfortunate shortcomings of PHP's parser. This will work:
$example = $this->example;
$min = $example::MIN_VALUE;
This won't:
$min = $this->example::MIN_VALUE;
Edit:
This issue is documented in PHP bug #63789: https://bugs.php.net/bug.php?id=63789
It has been fixed, but you will have to wait until PHP's next major release (7).
It is a class constant. There is no need (and indeed no means) whatsoever to access it in an instance-based way.
You should just access it as Example::MIN_VALUE to eliminate any confusion.
PHP > 5.3 allows access via an instance as you have shown (i.e. $class_instance::CLASS_CONSTANT) but this is still not to be confused with a property of that instance which can be accessed via -> (if public of course).
Is there a way how to access a constant with "$this"
You don't need to access a constant with $this, because $this refers to the current instanciated object of a class. constants can be accessed without instantiating an object.
Is there a good reason or is it just a language construct ...
A constant, as it's name implies, it's a constant value, meaning the value of that variable won't change during execution, that's why you don't need to instantiate an object to access its value.
Hope it's clear !

How to call method in class variable?

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.

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.

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