|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2019-06-28 10:26 UTC] dirk dot gerigk at tui dot com
 Description:
------------
Maybe it is a not implemented yet in alpha1, 
but i found a unexpected behavior when using __set / __get.
I will only point to one issue i found. 
So, when you use __set in a class and typ-hint a property, 
the __set method is always called.
Side Note (other issue):
Is it normal that you have to make every type-hinted property nullable?
Because when you have: public string $bar; 
And do: (new A)->bar;
You get: Fatal error: Uncaught TypeError: Typed property A::$bar must be string, null used
Is that wanted in that way? 
Test script:
---------------
class A {
    public string $bar;
    public $foo;
    final public function __get($name){
        print "get_$name ";
    }
    final public function __set($name,$arg){
        print "set_$name ";
    }
}
$obj = new A;
$obj->bar='';
$obj->foo='';
var_export($obj);
Expected result:
----------------
A::__set_state(array( 'bar' => '', 'foo' => '', ))
Actual result:
--------------
set_bar A::__set_state(array( 'foo' => '', ))
PatchesPull Requests
Pull requests: 
 HistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 00:00:01 2025 UTC | 
This is working "as intended", though I agree that the behavior is quite surprising. Typed properties start out uninitialized/unset and accessing unset properties causes calls to __get/__set. If you can, don't use __set. If you can't, use public ?string $bar = null; to explicitly initialize it the property to null, though you will have to deal with the consequences of that. It would be nice to have a way to bypass __set when assigning to an unset property (including uninitialized typed properties), but I don't see any obvious way to support that.