0

The program

<?php
class T
    {
    var $A;
    } // class T

$Cur=new T();
$Cur->A='test';
$Cur->B='test';
?>

Runs without error, but I expect an error when referencing undefined property B.

I've searched the Web and cannot find an explanation.

David Spector
  • 1,250
  • 12
  • 20
  • 6
    It is defined. You're creating `B` and assigning it a value when you do `$Cur->B`; Try doing `print_r` before and after you do `$Cur->B`. – DrZoo Jun 26 '19 at 18:20
  • 1
    As DrZoo mentions above, that above there is the explicit definition of those variables. However, you *can't* do anything with them before you declare them (i.e. `echo $Cur->A` isn't valid if you don't declare it, either inside the class or outside on the object). – Qirel Jun 26 '19 at 18:29
  • 1
    In PHP assignment creates an object or variable if it doesn't already exist, and taking the value of a non-existing variable returns undefined instead of an error. You never need to declare variables like in C++. This can make debugging typos exciting and fun! – Dave S Jun 26 '19 at 18:35
  • It is the nature of dynamic variables. PHP is trying to be helpful! PHP will create a variable by assigning a value to a name. A property of a class is a variable! If you assign a value to a property that doesn't exist on a class. It will create it as a public property. It is just the nature of the language. ;-/ You can setup safeguards on classes as already mentioned. It is why testing is so important with dynamic languages, They are a lot of fun though! – Ryan Vincent Jun 26 '19 at 19:53
  • I hadn't expected PHP to be quite THAT dynamic, because it already offers semantic arrays that work that way. Since PHP supports declarations of properties, I expected undeclared property references to be an error. PHP is certainly beyond my expectations, but not in a good way. The solution in the selected question and answer works but is in my opinion a workaround for bad design. For a current program, fixed object property declarations would have made debugging easier, so I will find another solution. I like to use class static constant and variables: thankfully, they are NOT dynamic! – David Spector Jun 27 '19 at 00:12

0 Answers0