-2

I'm experiencing an issue with class inheritance in PHP and I'm confused in regard to the causes as well as the workarounds. Please take a look at the code below:

    class Vehicle {
        public $properties = array();

        public function funky($property) {
         echo json_encode($this->properties) . PHP_EOL;
         echo json_encode(isset($this->properties[$property])) . PHP_EOL;
         echo json_encode($this->properties[$property]) . PHP_EOL;
        }
    }

    class Car extends Vehicle {
         public $properties = array('colour' => null, 'size' => null, 'fuel' => null);
    }

    $car = new Car();
    $car->funky('colour');

This prints:

    {"colour":null,"size":null,"fuel":null}
    false
    null

If I try with this child class instead where the array is initialized with non-null values:

    class Car extends Vehicle {
        public $properties = array('colour' => 'blue', 'size' => 8, 'fuel' => 'gas');
    }

Then I actually get what I expect:

    {"colour":"blue","size":8,"fuel":"gas"}
    true
    "blue"

This doesn't really make sense to me. My guess is that if the child class initializes the array with null values then it doesn't really care to actually create the array elements. However, this comes in conflict with how PHP seems to work with variables. For example:

    $ar = array('takis' => null);
    echo json_encode(isset($ar));

This prints "true"! Is there a reasonable explanation for that? What would you suggest as a workaround?

Thank you in advance :-)

verminoz
  • 15
  • 4

1 Answers1

0

isset returns true if the variable exists and is not null, otherwise it returns false.
If you need to check whether the array index exists regardless of its value use array_key_exists.

Also see The Definitive Guide To PHP's isset And empty.

deceze
  • 510,633
  • 85
  • 743
  • 889