RaoufOsman Posted February 24, 2014 Share Posted February 24, 2014 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. Quote Link to comment https://forums.phpfreaks.com/topic/286482-having-trouble-understanding-some-php-code/ Share on other sites More sharing options...
Solution jairathnem Posted February 24, 2014 Solution Share Posted February 24, 2014 $x = the variable (array) = what to typecast to. In this case array $child = object of a class tid = variable of the class experts, please correct me if I am wrong. Quote Link to comment https://forums.phpfreaks.com/topic/286482-having-trouble-understanding-some-php-code/#findComment-1470413 Share on other sites More sharing options...
.josh Posted February 24, 2014 Share Posted February 24, 2014 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. Quote Link to comment https://forums.phpfreaks.com/topic/286482-having-trouble-understanding-some-php-code/#findComment-1470421 Share on other sites More sharing options...
RaoufOsman Posted February 24, 2014 Author Share Posted February 24, 2014 You guys are great!! Jairathnem your answer made everything click. Thanks Josh for the clarification. Btw good guess because that's basically what it is doing. Quote Link to comment https://forums.phpfreaks.com/topic/286482-having-trouble-understanding-some-php-code/#findComment-1470423 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.