I'm getting this error in php. I'm trying to use substr in a class. Here is my code:
<?php
Class Test{
public $name = "for testing only";
public $part = substr($this->name, 5, 2);
public function show() {
echo $this->part;
echo $this->name."\n";
}
public function change($data) {
$this->name = $data;
}
}
$myTest = new Test();
$myTest->show();
$myTest->change("something else");
$myTest->show();
?>
Aptana highlights the ( and the first , on line 4 and tells me "syntax error".
Netbeans highlights the whole line 4 and tells me
unexpected: ( expected =>,::,',`,OR,XOR and lots more.
When I run the code as a PHP script using Aptana Run menu the error message is:
Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\path\to\file\test.php on line 4
When I change $this->name
to $name
the Aptana only highlights the (
When I use this code from Interactive Mode in Windows it seems to work:
Interactive mode enabled
<?php $name = "for testing only";
$part = substr($name, 5, 2);
echo $name; echo $part;
?>
^Z
for testing onlyes
Does anyone know what I am doing wrong? Is substr()
allowed inside a class?
The above is not valid syntax. From the manual:
In other words, the value of this property can only be an integer, float, string, boolean, or empty array. Expressions are not allowed.
To remedy this you can initialize that value inside of your constructor: