Why implicit property declarations in PHP?

I'm wondering why the PHP language allows an implicit property declaration when most languages ​​need to define properties inside the class declaration itself (see code below). Is there a practical use for this type of coding style?

$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}
0
source share
3 answers

Use case are value objects

$a = new stdClass;
$a->something = 12;
$a->somethingElse = 'Hello World';
myFunction ($a);

This allows you to create some objects that simply carry structured data (something like structsin other languages), without having to define a class for it.

Another point is that since PHP is weakly typed anyway, there is no reason to ban it. If you need something stronger, overweite__set()

public function __set ($propertyName, $value) {
  throw new Exception("Undefined Property $propertyName");
}
+4
source

, ))

+1

I would say that this is due to the fact that php was and remains rather weak in relation to these data types, and to maintain at least a little downward compatibility for scripts written in an earlier version of php (<5).

+1
source

All Articles