1
<?php

class ser {

    public $a;

}

$x = new ser;
$x->b = 10;

var_dump($x);

Something like this.

Class ser has only $a property, but we can set $b to new object of this class and it works despite this class doesn't have any $b property

output

E:\XAMPP\htdocs\fun\test2.php:12:
object(kurde)[1]
  public 'a' => null
  public 'b' => int 10

Why this works?

Why we can add property and set it to this class while it doesn't belong exactly to this class?

How is that possible and why is that possible?

Any purpose? Sense of making this possible?

7
  • 3
    Because you can... Aint PHP wonderful Commented Aug 24, 2017 at 21:45
  • Why is this allowed? Why we can do this? What is purpose of this and sense? @RiggsFolly Commented Aug 24, 2017 at 21:46
  • You can do it in javascript also :) and Python :0 :) Commented Aug 24, 2017 at 21:47
  • It's actually quite useful if you're in a framework and you want to pass some extra data with an object for which you might not have a property on that class. Commented Aug 24, 2017 at 21:55
  • @Bram if there is a framework, which is built around this behaviour, you probably should stay away from it. Commented Aug 24, 2017 at 21:56

1 Answer 1

3

This is what PHP refers to as "overloading". This is different to overloading in almost any other object oriented language.

If you do not like it, you can use the __set magic method to throw an exception if a non-existent property is set:

public function __set($name, $value) {
    throw new \Exception('Property "'.$name.'" does not exist')
}

You can tell from the comments on the documentation what the general consensus of this "feature" is.

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.