tags:

views:

84

answers:

3

hey guys , im writing a class and im wondering how i can write a condition statement in this way :

$this->referer= (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';

i need to find my user_id and this is the usual condtion :

    if(is_user($user)){ 
        $cookie=cookiedecode($user);
        $user_id=intval($cookie[0]);
    }

and i think it should be something like this :

    $this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];

but it didnt work

+2  A: 

what about this way :

    if(is_user($user)){ 
        $cookie=cookiedecode($user);
        $this->user_id =intval($cookie[0]);
    }
farshad Ghazanfari
+2  A: 

The ternary operator should be used sparingly, and only when the logic is simple enough to maintain readability! Get too complex and the shorthand outweighs its usefulness by being difficult to understand.

The ternary operator will only work with one variable assignement at a time. Here is the manual example

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

Your example

$this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];

will assign the user_id to cookiedecode($user) if is_user() returns true, or to $cookie[0] if not.

In light of this:

you should keep your existing code structure!!

Andy
but my friend , the example u gave me is exactly what i used and shown in my question , i tried that statement but didnt work for me , and return 0 $this->user_id = (is_user($user)) ? (cookiedecode($user)) : $cookie[0];
Mac Taylor
Mac, he was explaining why your code doesn't work.
Syntax Error
A: 
 if(is_user($user)){ 
        $cookie=cookiedecode($user);
        $this->user_id =intval($cookie[0]);
    }

   I didn't see any ELSE statement in your code and i don't understand on why do you want to use short form of conditional statement.
Soe Naung Win