如何在 class 中初始化 属性 的方式使用条件?

How can I use a condition on the way of initializing a property in the class?

我有一个受保护的 属性,我需要对其进行动态初始化。我的意思是我需要为它设定一个条件。像这样:

protected $redirectTo = if ( Session::has("vocher_id") ) ? '/activated' : '/home';

但显然上面的语法在 PHP 中无效。知道我该怎么做吗?

在不知道您到底想要什么的情况下,这里有一些您可能会使用的示例...

<?php

class Foo {

    protected $redirect;

    public function __construct() {
        $this->redirect = (Session::has("vocher_id") ) ? '/activated' : '/home';
    }

    // More Methods that Do other stuff
}

// Or to make it more "modular" i.e not hardcode things inside the class

class Bar {

    protected $redirect;

    public function __construct($redirect) {
        $this->redirect = $redirect;
    }

    // More Methods that Do other stuff
}

// Set the redirect when instantiating the class
$bar = new Bar((Session::has("vocher_id")) ? '/activated' : '/home');

或者你可以创建一个 Setter 方法(留给你做的练习)...有很多方法,所以请阅读 类 等