-1

I googled this and browsed stack overflow already. I am trying to shorten my code and I have this working method below I want to rewrite in ternary style. Can someone tell me if this is possible and if so what im doing wrong. Thanks.

public function __get($field){ //refactor this using ternary method
    if($field == 'user_id'){
        return $this->uid;
    } else {
        return $this->fields[$field];
    }
}

I started with this:

($field == 'user_id') return $this->uid : return $this->fields[$field];

and it gives me a unexpected return error.

I tried using another stack overflow solution that listed the return before the values and that didnt work.

return $field == 'user_id' ? $this->uid : $this->fields[$field];

This gives me some other error about unexpected public, like my method isnt closing correctly.

peb7268
  • 23
  • 4

1 Answers1

1

I'm going to guess it's something like this; you refactored your code to this:

public function __get($field){ //refactor this using ternary method
        return $field == 'user_id' ? $this->uid : $this->fields[$field];
    }
}

public function otherfunction() { /* ... */ }

The braces don't match and therefore it closes the class definition and the next parser error is 'unexpected public' :)

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309