Forum Moderators: coopster

Message Too Old, No Replies

(object)

arrays as objects as arrays ...

         

nyteshade

4:42 pm on Sep 16, 2011 (gmt 0)

10+ Year Member



I just ran across something:

$stateAbbrv = (object) array("DC","OH","VA","MI","TX");


The (object) keyword? I've never seen. It allows var_dump to provide additional info on the array as an object but I thought that arrays were objects? Anyone know anything about (object)? I tried php manual and several searches with no luck. Thanks all.

coopster

5:31 pm on Sep 16, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can type cast any variable to the type desired, including object.

$string = (string) (10*10); // Creates a string of '100'
$integer = (integer) '100'; // Creates an integer of 100

More reading ...
[php.net...]
[php.net...]

Readie

5:45 pm on Sep 16, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I thought that arrays were objects

Arrays are collections of data. Essentially a variable containing more variables.

While part of an object is data, it also typically has internal methods associated with it, and has some very unique behavior with regards to statics.

penders

6:30 pm on Sep 16, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I thought that arrays were objects


In JavaScript they are.

$stateAbbrv = (object) array("DC","OH","VA","MI","TX");


Be careful about casting arrays with numeric indices (such as this one) to objects since you won't be able to access any of the property values directly without using a foreach() construct.

It allows var_dump to provide additional info on the array...


What additional info?

nyteshade

9:18 pm on Sep 16, 2011 (gmt 0)

10+ Year Member



Thanks everyone! I didn't know you could type cast with (object) . I'm on my 3rd PHP book: "PHP Objects, Patterns, and Practice"; so far, haven't seen (object) syntax. Is it a method?

//for penders:

$stateAbbrv = array("DC","OH","VA","MI","TX");
var_dump($stateAbbrv);

array(5) {
[0]=>
string(2) "DC"
[1]=>
string(2) "OH"
[2]=>
string(2) "VA"
[3]=>
string(2) "MI"
[4]=>
string(2) "TX"
}

$stateAbbrv = (object) array("DC","OH","VA","MI","TX");
var_dump($stateAbbrv);

object(stdClass)#1 (5) {
[0]=>
string(2) "DC"
[1]=>
string(2) "OH"
[2]=>
string(2) "VA"
[3]=>
string(2) "MI"
[4]=>
string(2) "TX"
}

nyteshade

9:26 pm on Sep 16, 2011 (gmt 0)

10+ Year Member



coopster - thanks for the links, much clearer on the casting thing now... and penders, yes, I just came away from two months of js dom scripting lessons and made the assumption everything is an object, imagine that.

nyteshade

1:12 pm on Oct 5, 2011 (gmt 0)

10+ Year Member



My previous statement regarding the absence of type casting from my earlier readings was incorrect. Type casting was explained in the earlier books I've read but only cursorily, like a paragraph, but it was there.