skip to Main Content

I have a method at a Model like this:

public function questionOwner($id)
    {
        if (auth()->user()->id == $id) {
           return true;
        }else{
            return false;
        }
    }

Now I wanted to refactor this function so I tried this:

public function queOwner($id)
    {
        return !! auth()->user()->id == $id;
    }

So if auth()->user()->id was not equals to $id, then it should return false because of !! but I don’t know why it always return TRUE!

So if you know what’s going wrong here and how can I refactor this function, please let me know, thanks…

3

Answers


  1. Maybe that’s what you mean?

    public function queOwner($id)
    {
        return auth()->user()->id === $id;
    }
    
    Login or Signup to reply.
  2. you could do in two ways

        public function questionOwner($id)
        {
    
            return Auth::user()->id == $id
        }
    

    or

        public function questionOwner($id)
        {
           return Auth::user()->id==$id?true:false;
        }
    
    Login or Signup to reply.
  3. <?php
    // Pre-requirement
        function auth() {
            return new class { 
               public function user() {
                   return new class {
                       public $id = 15;
                   };
               }
            };
        }
    
    // Client code
    class A {
        public function queOwner($id)
        {
            // According to the priority https://www.php.net/manual/en/language.operators.precedence.php
            // double !! here implies only the left side of the comparison, so
            // expression here is "return (!(! auth()->user()->id)) == $id)
            // Comparison here performs after the type juggling.
            // For example:
            // "!(! 15)" -> "not (not 15)" -> "not 0" -> true
            // if $id is equal to any non-zero integer number, it will be interpreted as true,
            // Hence, if auth()->user()->id is not 0 and $id is not 0, this statement always returns true, otherwise - false.
            return !! auth()->user()->id == $id;
        }
    }
    
    
    // Examples
    var_dump((new A())->queOwner(15)); // true
    var_dump((new A())->queOwner(13)); // true
    var_dump((new A())->queOwner(0)); // false
    

    A full example could be found here: https://php.band/D2pzfPA2t

    So, to avoid such a situation, use Strict comparison (Identical) or (better) strict typing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search