Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP property doesn't exist but no errors thrown when used

Tags:

oop

php

So I came across a code like this and it makes use of one of the Bar class properties called testObj while it's not defined so I expected this to be wrong but I tested it my own and no errors:

    <?php
class Foo{
    public function __construct()
    {
        echo 'Echo From Foo';
    }
}
class Bar{
    public function __construct(Foo $foo)
    {
        $this->testObj = $foo;
    }
}

$bar = new Bar(new Foo);

Why is that so? Does this have anything to do with the "Dynamic/Loose Type"ness of PHP or something else?

like image 615
aderchox Avatar asked Aug 05 '26 13:08

aderchox


2 Answers

Properties can be defined dynamically and their visibility is defaulted to public as can be seen in the example below:

class X {
  public function test()
  {
    $this->y = 'test';
  }
}

$x = new X();

$x->test();

echo $x->y; // test

You can also do this without being in the class, so if I wanted to add another property, I could just do the following:

class X {
  public function test()
  {
    $this->y = 'test';
  }
}

$x = new X();

$x->test();

echo $x->y; // test

$x->z = 'blah';

echo $x->z; // blah

Remember, when a class in instantized it is just an object which can be manipulated as any other object.

Note: If I don't call test() in the above code, it will result it an error (undefined property) because the variable has not been defined except in the test() function.

Live Example

Repl

like image 197
Script47 Avatar answered Aug 07 '26 02:08

Script47


This is perfectly normal, you can dynamicaly assign every propteries to a PHP class without error. Event if you should declare it properly to keep track of your object structure. If you want it to throw an error, you can use the __get magic function and ReflectionClass to determine wich property is setted and wich you can't set even if I didn't see any advantage of doing this.

like image 43
Jordan Breton Avatar answered Aug 07 '26 03:08

Jordan Breton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!