关于php:解析错误:语法错误,Parse error: syntax error, unexpected ‘(‘, expecting ‘,’ or ‘;’ in

Parse error: syntax error, unexpected '(', expecting ',' or ';' in

我收到以下分析错误:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in
H:\Programs\USBWebserver
v8.5\8.5
oot\oopforum\func
egister.class.php on line 7

这与我班的以下代码行有关:

1
private $random_name = rand(1000,9999).rand(1000,9999).rand(1000,9999).rand(1000,9999);

我不明白这行代码为什么会导致分析错误?

以下是一些周边代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class register{
    public $post_data = array();
        private $dbh;
        private $allowed_type = array('image/jpeg','image/png','image/gif');
        private $random_name = rand(1000,9999).rand(1000,9999).rand(1000,9999).rand(1000,9999);
        private $path = 'img/thumb_/'.$random_name. $_FILES['file']['name'];
        private $max_width = 4040;
        private $max_height = 4040;
        private $max_size = 5242880;
        private $temp_dir = $_FILES['file']['tmp_name'];
        private $image_type = $_FILES['file']['type'];
        private $image_size = $_FILES['file']['size'];
        private $image_name = $_FILES['file']['name'];
        private $image_dimensions = getimagesize($temp_dir);
        private $image_width = $image_dimensions[0]; // Image width
        private $image_height = $image_dimensions[1]; // Image height
        private $error = array();

        public function __construct($post_data, PDO $dbh){
        $this->post_data = array_map('trim', $post_data);
        $this->dbh = $dbh;
        }
}

导致分析错误的原因是什么?


您不能将成员变量初始化为任何非静态的,并且您试图调用一个函数。

从手册中:

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.

解决方法是在构造函数中设置变量:

1
2
3
4
private $random_name;
public function __construct() {
    $this->random_name = rand(1000,9999).rand(1000,9999).rand(1000,9999).rand(1000,9999);
}


你不能这样做:

1
private $image_dimensions = getimagesize($temp_dir);

不能调用函数、变量和任何非静态的东西来设置类变量。