5

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?

3
  • 2
    PHP will allow you to add that property unless you explicitly tell it not to by overloading __set() and throwing an error when you do. Commented Oct 22, 2015 at 19:03
  • So, people may use empty classes just by declaring the class? Commented Oct 22, 2015 at 19:04
  • I've never had to use it, but I would guess it would be so that people can associate various data parts with a pre-defined out-the-box class, such as using the PHPMailer class to send an email and then saving to the class some sort of database id tracking, for the user whose email is just sent to, to record in the class who got the email sent to them. That's my guess... Commented Oct 22, 2015 at 19:55

1 Answer 1

3

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';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.