Hi guys,
I am a newbie in PHP, but experienced in other OOP languages, so sorry if my questions are maybe trivial for some of the forum members, but hope can get some answers for my questions.
Tried to google some info on the fact if PHP supports object casting, but could not find any useful answer, except one, but with a poor description.So is it possible in PHP to use object casting (I do not mean vasriable casting, like boolean, integer types)?
My example:
I define a class called Test with some logic, then create some objects of Test type. Then let's say I create an array of Test objects, so I can access any of the Test objects from the array by the array index. But I want to make sure that the returned array member for xy index is actually a type of Test. The logic above is maybe trivial, but I just tried to simplify what I want to achieve.
So now, how can I achieve this type of casting in PHP?The pseudocode is below:
//$ArrayList is an array of obejcts of Test type
//ArrayMember is an object, but want to make sure that it is actually of type of Test, so need an explicit casting
$ArrayMember = (Test)$ArrayList[xy];

I know that I could use the function get_class() for the array members to test whether they are of Test type, but I need to use casting rather than testing it.
Thank you
Ben

    i'm not sure there is object casting in php. object type hinting and testing for objects using the is_object() is pretty common. why not make your array as part of a class and use object type hinting to make sure you get the desired result. just a suggestion.

      I know that I could use the function get_class() for the array members to test whether they are of Test type, but I need to use casting rather than testing it.

      Why?

        laserlight wrote:

        Why?

        Possibly to avoid errors when accessed. Though if it the case it is not defensive and a bit bad.

        A list/map implementation using the iterator interface and type hinting would guarantee the data passed into the put/add method is of the desired type and block against this need.

        http://ramikayyali.com/archives/2005/02/25/iterators

        They are most useful.

          Possibly to avoid errors when accessed.

          That does not explain "I need to use casting rather than testing it", which is the core of my question. Note that all other solutions except type casting are unsatisfactory since benjib98 needs to use casting for some unspecified reason.

            laserlight wrote:

            That does not explain "I need to use casting rather than testing it", which is the core of my question. Note that all other solutions except type casting are unsatisfactory since benjib98 needs to use casting for some unspecified reason.

            Well as it is not a native feature of php a custom handler can be written.

            //not tested and there are more methods for classes that deal with parent classes etc

            function caster( $value, $require_type )
            {
               if( get_class($value) != $require_type )
               {
                    return new $require_type();
               }
               return $value;
            }
            

            It does raise all sorts of issues which I admit are domain specific. Really it has to be decided on what is supposed to happen when accidently casting from an int to custom class in a case per case. Casting to an incorrect class should cause a class cast exception if there was one which would in turn still need to use checking. I really don't see PHP adding this feature unchecked which the original question asked for.

            Anyway enough playing for now.. I'll get spanked.

              As was mentioned, type hints in PHP5 are the closest PHP gets to (up)casting objects.

              class Foo{}
              class Bar extends Foo{}
              function isAFoo( Foo $foo )
              {}
              $bar = new Bar;
              isAFoo( $bar );
              

              Since the link to the Iterators example appears broken, here's a quick example of how PHP's array operators can be overloaded to allow cast-like behaviour

              class Foo{}
              class Bar{}
              class FooCastArray extends ArrayObject
              {
                // Override to allow type checking
                function offsetGet( $index )
                {
              	$val = parent::offsetGet( $index );
              	if( !$val instanceof Foo )
              	{
              		trigger_error( 'must be a Foo;', E_USER_ERROR ); // or throw Exception type perhaps
              	}
                }
              }
              $fooarray = new FooCastArray;
              $fooarray[] = new Foo;
              $fooarray[] = new Bar;
              $fooarray[0]; // OK
              $fooarray[1]; // Fatal error since Bar is not a Foo
              

              Admittedly it's alot of work. Most people would rely on duck typing rather than putting in this much effort 🙂

                Write a Reply...