php syntax error unexpected ')'

1.2k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER
public $part = substr($this->file, 5, 2);

The above is not valid syntax. From the manual:

Class member variables are called "properties". They 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.

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:

public $part;

public function __construct() {
    $this->part = substr($this->name, 5, 2)
}
2
On

You cannot have expression(s) there. You should apply substr() inside the __construct.

Also $this->file doesn't seem to be defined anywhere in your class. Maybe you want this:

function __construct(){
   $this->part = substr($this->name, 5, 2);
}
0
On

You cannot declare an expression as a default value.

1
On

Try applying substr in a constructor.

Also $this->file is giving me Undefined property: Test::$file in - on line 7 since it's not defined...

<?php
Class Test{
    public $name = "for testing only";
    public $part;

    function __construct() {
        $this->part = substr($this->file, 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();
?>