Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with PHP Class Properties

Tags:

php

I have created a new class named Player with 2 properties:

  1. name

  2. ID

I have no idea how the following code worked to me, that's why I'm asking you:

<?php
$player = new Player();
$player->name = "Someone";
$player->ID = 123;
$player->color = "Red"; // Why it worked?
echo $player->color; // Worked great too!
?>

I could set a property color and use it when I haven't even declared it in my class file. How is it possible?

like image 626
EliKo Avatar asked Oct 19 '22 23:10

EliKo


1 Answers

In PHP, the feature is called property overloading (the "overloading" term is misused! it should've been something like "interpreter hooks", instead).

Overloading in PHP provides means to dynamically "create" properties and methods.qoute

You can use the dynamic properties as if they've been declared in the class definition; like:

class A {
}

$a = new A();
$a->myProperty = 'something';
like image 77
someOne Avatar answered Nov 15 '22 06:11

someOne