Wednesday, 22 January 2020

How to permanently typecast class properties in PHP?

I have been reading the "Visibility" section of the PHP manual, and in the first comment, someone mentions:

OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) -- another huge mistake.

Consider this example:

class base {
    public $foo = 1;
}

$first = new base();

(string)$first->foo; //I thought just this expression would typecast
var_dump($first->foo); //but I found it still is int


$first->foo = (string)$first->foo;    
var_dump($first->foo); //ok so public props can be typecasted

Is it just with the protected and private properties that we cannot change their type from outside? Or does that apply to public properties, too?



from How to permanently typecast class properties in PHP?

No comments:

Post a Comment