How can I easily assign a value (short notatio) to a property of a nested class in php 8+?

26 Views Asked by At

If you don't declare the class, PHP >=8 creates a fatal error. Is there a short form for nested classes?

$obj -> key1 -> var1 = "quick and easy";

Or is this the only possible way:

$obj =   new stdClass();
$obj -> key1 =  new stdClass();
$obj -> key1 -> var1 ="nasty"; 

respectively

$obj = (object)[ 'key1' => (object)[ 'var1' => "to many brackes and quotes" ],];

I truly prefer notation without quotes and brackets. Readability is -- I correct myself -- possible, but for a quick but still pretty option, there seems to be nothing available (took me half an hour to pretty print the lines below ...).

Readability options

array:
$arr = (array) [ 
       'key1'  => (array)[
                  'var1' => "many quotes but well readable"    ,
                  'var2' => "due to layout"                    ,
                   ],
       'key2'  => (int)     123                                ,
       'nokey' => (string)  "quick and pretty missing"         ,
       ];

object:
$obj = (object) [ 
       'key1'  => (object)[
                  'var1' =>  "many quotes but well readable"   ,
                  'var2' =>  "due to layout"                   ,
                   ],
       'key2'  => (int)      123                               ,
       'nokey' => (string)   "quick and pretty missing"        ,
       ];
1

There are 1 best solutions below

0
Wimanicesir On

I agree that there are more quotes and brackets when creating a class vs an array. However I strongly disagree about the readability part as this is just a matter of formatting.

A few tips:

  1. Always put a new entry on a new line
  2. Align all keys to the biggest one (probably your IDE can do this for u)
  3. Use the same structure for all properties of an entry

An example could be:

[
    'contact_id'                 => ['TYPE' => 'INT', 'INDEX' => true],
    'relation_id'                => ['TYPE' => 'INT', 'INDEX' => true],
    'relation_contact_email'     => ['TYPE' => 'TEXT'],
]

While doing this for an object:

$properties = new stdClass();

$contact_id = new stdClass();
$contact_id->TYPE = 'INT';
$contact_id->INDEX = true;
$properties->contact_id = $contact_id;

$relation_id = new stdClass();
$relation_id->TYPE = 'INT';
$relation_id->INDEX = true;
$properties->relation_id = $relation_id;

$relation_contact_email = new stdClass();
$relation_contact_email->TYPE = 'TEXT';
$properties->relation_contact_email = $relation_contact_email;

I think I don't need to make a further case on what is more readable and easier to use. The syntax of a language is not something your prefer, but something you need to learn.