4

Why doesn't PHP throw an error on line 7?

https://ideone.com/DHMLCY

<?php

class Test {
    public function __construct(){

        $name = 123;
        $this->$name = 'Test';
        var_dump($this->$name);


        $this->123 = 'Test2';
        var_dump($this->123);

    }
}

$test = new Test();
var_dump($test);

I always thought, that class fields couldn't start with numbers. But that doesn't seem to be the case if the number is in a variable.

TMH
  • 6,096
  • 7
  • 51
  • 88

1 Answers1

5

I believe this is because of the dynamic nature of PHP variables.

If you read the vardump of the defined class property:

 object(Test)#1 (1) { ["123"]=> string(4) "Test" }

You can see its (index is) a string, not a integer as you're expecting it to be

JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29