2017-12-12 20 views
-1

동적으로 초기화해야하는 보호 된 속성이 있습니다. 나는 그것의 상태에 조건을 넣어야 함을 의미한다. 다음과 같은 것 :클래스의 속성을 초기화하는 방법에 조건을 사용하려면 어떻게해야합니까?

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

명백하게 위의 구문은 PHP에서 유효하지 않습니다. 어떻게 그런 생각을 할 수 있을까요?

여기 후 당신이 사용할 수있는 몇 가지 예입니다 정확히 모른 채
+2

과제가 상수 값이 아닌 경우 [PHP 문서 도구]에 따라 생성자에서 설정해야합니다. (http://php.net/manual/en/language. oop5.properties.php)'이 선언에는 초기화가 포함될 수 있지만이 초기화는 상수 값이어야합니다. 즉, 컴파일시 평가가 가능해야하며 런타임 정보에 의존해서는 안됩니다 평가했다. –

답변

0

...

<?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'); 

또는 당신은 세터 방법 (운동 당신을 위해 왼쪽 만들 수 있습니다 해야 할 일) ... 여러 가지 방법이 있으므로 수업 등을 읽으십시오.