【问题标题】:php syntax error unexpected ')'php语法错误意外')'
【发布时间】:2014-11-18 21:01:32
【问题描述】:

我在 php.ini 中遇到了这个错误。我正在尝试在课程中使用 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 并告诉我

unexpected: ( 预期 =>,::,',`,OR,XOR 等等。

当我使用 Aptana 运行菜单将代码作为 PHP 脚本运行时,错误消息是:

解析错误:语法错误,意外 '(',期待 ',' 或 ';' in C:\path\to\file\test.php 在第 4 行

当我将 $this-&gt;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() 是否允许在一个类中?

【问题讨论】:

  • 这个$this-&gt;file在你的班级中不存在!
  • @Rizier123 :你是对的。我已经编辑了问题。

标签: php class substr


【解决方案1】:

那里不能有表达式。 您应该在__construct 中应用substr()

另外$this-&gt;file 似乎没有在您的班级中的任何地方定义。也许你想要这个:

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

【讨论】:

  • 抱歉,“文件”应该是“名称”。我编辑了问题以符合要求。
  • 查看 __construct 部分
【解决方案2】:
public $part = substr($this->file, 5, 2);

以上是不是有效的语法。来自the manual

类成员变量称为“属性”。它们是通过使用关键字 public、protected 或 private 之一来定义的,然后是一个普通的变量声明。此声明可能包含一个初始化,但此初始化必须是一个常量值——也就是说,它必须能够在编译时进行评估,并且不能依赖运行时信息才能进行评估。

也就是说,这个属性的值只能是整数、浮点数、字符串、布尔值或空数组。不允许使用表达式。

要解决这个问题,您可以在构造函数中初始化该值:

public $part;

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

【讨论】:

    【解决方案3】:

    您不能将表达式声明为默认值。

    【讨论】:

      【解决方案4】:

      尝试在构造函数中应用 substr。

      还有$this-&gt;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();
      ?>
      

      【讨论】:

      • 对不起,应该是 $test->name。我将编辑原件。
      猜你喜欢
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2012-05-16
      • 2011-02-09
      • 1970-01-01
      • 2014-06-27
      • 2015-05-28
      • 2012-11-03
      相关资源
      最近更新 更多