PHP 个变量在 class 中使用其他变量作为它们的初始值

PHP variables using other variables as their initial value in a class

我有一个 class 并且在里面我正在初始化一些变量。我将第一个变量设置为 100,然后我想将其用于接下来的几个变量。

我的 IDE 给出了以下错误并且代码没有打印我的变量:

syntax error, unexpected '$defaultWidthHeight' (T_VARIABLE)

无效:

class generateRandomThumbnails
{
    private $defaultWidthHeight = 100;
    private $width = $defaultWidthHeight; // This is not allowed?
    private $height = $defaultWidthHeight; // This is not allowed?

    public function echoTest(){
        return $this->height;
    }
}

输出:无!

有效:

class generateRandomThumbnails
{
    private $defaultWidthHeight = 100;
    private $width = 100; // This is allowed.
    private $height = 100; // This is allowed.

    public function echoTest(){
        return $this->height;
    }
}

输出:100

我是如何调用函数的:(我认为这与我的示例无关,但包括在内以防我在这里做错事)

<?php
require_once 'generateRandomThumbnail.php';
$image = new generateRandomThumbnail();

$test = $image->echoTest();
echo $test;
?>

您不能将 "dynamic" 值分配给 class 声明中的 class 属性。您可以像对每个 属性 那样分配 100,或者按照您在评论中所说的那样在构造函数中进行分配。

有关 class 属性 的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.properties.php

引自那里:

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.

基于 Rizier123、John Conde 和 Dvir Azulay,有两种主要方法可以实现此目的:

使用构造函数:

class generateRandomThumbnail
{
    private $defaultWidthHeight = 150;
    private $width = 0;
    private $height = 0;

    function __construct(){
        $this->width = $this->defaultWidthHeight;
        $this->height = $this->defaultWidthHeight;
    }

    public function echoTest(){
        return $this->height;
    }
}

使用常数:

class generateRandomThumbnail
{
    const DEFAULT_SIZE = 150;
    private $width = self::DEFAULT_SIZE;
    private $height = self::DEFAULT_SIZE;

    public function echoTest(){
        return $this->height;
    }
}