Jump to content

Having trouble understanding some PHP code

Go to solution Solved by jairathnem,

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. 
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 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.