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

时间:2017-12-12 10:10:10

标签: php oop initialization conditional

我有一个受保护的属性,我需要动态初始化它。我的意思是我需要在它的路上设置一个条件。像这样:

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

但显然上面的语法在PHP中无效。我知道怎么做这样的事情?

1 个答案:

答案 0 :(得分:0)

如果不确切知道自己的目标,可以使用以下示例......

<?php

class Foo {

    protected $redirect;

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

    // More Methods that Do other stuff
}

OR

// 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方法(一个练习留给你)...有很多方法,所以做一些阅读课程等。