我在php中收到此错误。我正在尝试在课堂上使用substr。 这是我的代码:
<?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突出显示(第一行,第4行并告诉我“语法错误”。
Netbeans突出了整个第4行并告诉我
意外:(预期=&gt;,::,',`,OR,XOR等等。
当我使用Aptana Run菜单将代码作为PHP脚本运行时,错误消息为:
解析错误:语法错误,意外'(',期待','或';'in 第4行的C:\ path \ to \ file \ test.php
当我将$this->name
更改为$name
时,Aptana只突出显示(
当我在Windows中使用交互模式下的代码时,似乎可以工作:
Interactive mode enabled
<?php $name = "for testing only";
$part = substr($name, 5, 2);
echo $name; echo $part;
?>
^Z
for testing onlyes
有谁知道我做错了什么?在课堂内是否允许substr()
?
答案 0 :(得分:4)
你不能有表情。
您应该在substr()
。
__construct
同样$this->file
似乎没有在你班级的任何地方定义。也许你想要这个:
function __construct(){
$this->part = substr($this->name, 5, 2);
}
答案 1 :(得分:3)
public $part = substr($this->file, 5, 2);
以上是不有效语法。来自the manual:
类成员变量称为“属性”。它们通过使用public,protected或private之一,然后是普通变量声明来定义。此声明可能包括初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估。
换句话说,此属性的值只能是整数,浮点数,字符串,布尔值或空数组。表达是不允许的。
要解决此问题,您可以在构造函数中初始化该值:
public $part;
public function __construct() {
$this->part = substr($this->name, 5, 2)
}
答案 2 :(得分:0)
您不能将表达式声明为默认值。
答案 3 :(得分:0)
尝试在构造函数中应用substr。
同样$this->file
正在给我Undefined property: Test::$file in - on line 7
,因为它没有定义......
<?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();
?>