Luciano Nascimento
Luciano Nascimento

Reputation: 2600

IF condition inside an array

In trying to use an if condition inside an array, but its not working. How can I fix that?

Code:

public function behaviors()
{
    return array(
        'withRelated'=>array(
            'class'=>'ext.wr.WithRelatedBehavior',
        ),
        Yii::app()->controller->id != 'apiv1' ?
        'datetimeI18NBehavior'=>array(
            'class' => 'ext.DateTimeI18NBehavior',
        ), : false,
    );
}

Error:

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in .../models/Users.php on line 77

Upvotes: 1

Views: 1069

Answers (3)

QArea
QArea

Reputation: 4981

public function behaviors() {
return array(
'withRelated'=>array(
'class'=>'ext.wr.WithRelatedBehavior',
),
Yii::app()->controller->id != 'apiv1' ?
'datetimeI18NBehavior'=>array(
'class' => 'ext.DateTimeI18NBehavior',
) : false,
);
}

remove the comma after the parentheses

Upvotes: 0

Kalpesh
Kalpesh

Reputation: 5695

This is the proper approach to your problem.

public function behaviors()
{
    $arr = array(
        'withRelated'=>array(
            'class'=>'ext.wr.WithRelatedBehavior',
        )        
    );
    $bool = Yii::app()->controller->id != 'apiv1' ? true : false;
    if($bool) {
        $arr['datetimeI18NBehavior'] = array(
            'class' => 'ext.DateTimeI18NBehavior',
        );
    } else {
        $arr[] = false;
    }
}

Upvotes: 5

hsz
hsz

Reputation: 152266

Try with:

'datetimeI18NBehavior' => ( Yii::app()->controller->id != 'apiv1' ) ? array(
    'class' => 'ext.DateTimeI18NBehavior',
) : false,

Other (much clear) solution:

public function behaviors()
{
    $behaviors = array(
        'withRelated'=>array(
            'class'=>'ext.wr.WithRelatedBehavior',
        )
    );

    if ( Yii::app()->controller->id != 'apiv1' ) {
         $behaviors['datetimeI18NBehavior'] = array(
            'class' => 'ext.DateTimeI18NBehavior'
        );
    }

    return $behaviors;
}

Upvotes: 2

Related Questions