Jump to content

Having trouble understanding some PHP code


RaoufOsman

Recommended Posts

So I am an intern doing PHP development, the issue is I am having a hard time understanding what a colleague of mine wrote:

 

$x=(array) $child->tid;

$tagname = (string) $child->name[0];

 
Just in a broad sense why does he initialize $x = (array)? etc.. I never seen this syntax, my OOP isnt as well as it should be, but any help is appreciated. I cant post the code because my boss is wary of people stealing code. 
 
 

It's basically a cheap (and often dangerous) way to convert one variable type to another.

 

There's not enough info here to be sure, but if I had to guess, I'd say $child->tid is an object (like maybe a json object from a request or response or xml object) being converted to an array, most likely for no other reason than it being easier for whoever coded it to handle the data (e.g. loop through it).

 

$child->name[0] is probably already expected to be a string but is being typecasted to string type to be safe (e.g. maybe it's possible $child->name[0] could also be a number).

 

For the latter, that's usually not needed, since php is loosely typed and will do type conversion automatically. But there are some php functions that php fails on. For example, ctype_digit checks to see if a string only contains numbers, but if you try to do ctype_digit(12345) you will get an error (crazy, huh?), so you have to typecast to keep it from breaking.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.