SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    May 2003
    Location
    Auckland
    Posts
    309
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Converting between object types?

    Is there a method to convert an instance of an object to another class?

    e.g.

    PHP Code:
    class SimpleObject {}
    class 
    AdvancedObject {

        public function 
    AdvancedMethod()
        {

        }

    }

    $object1 = new SimpleObject();

    // cast
    $object1 = (AdvancedObject$object1;

    echo 
    $object1->AdvancedMethod(); 

  2. #2
    SitePoint Enthusiast csjc2662's Avatar
    Join Date
    Feb 2007
    Location
    Texas, USA
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well PHP doesn't support operator overloading so you would have to write a special member function to convert the types(objects)

    ie

    PHP Code:
    class SimpleObject {
        
        private 
    $example_value;
       
       function 
    AdvancedObjectCast($obj)
             {
             
    $this->example_value $obj->corresponding_value;
             
    // I believe this can also be assigned the object itself
             
    }

    }
    class 
    AdvancedObject {

        public 
    $corresponding_value;
      
    // to allow this to be a private value you would have to create a member function that returns the value and reference that above...  

        
    public function AdvancedMethod()
        {

        }

    }

    $object1 = new SimpleObject();

    // cast
    $object1 AdvancedObjectCast($object1);

    echo 
    $object1->AdvancedMethod(); 
    I know this can be abstracted more but that is the basic idea.
    James
    New links coming soon....

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Imminent View Post
    Is there a method to convert an instance of an object to another class?
    Yes, there are some methods, or, rather, dirty hacks, but that's a "you shouldn't want it" type of thing in the first place. Tell us more about your problem, perhaps we can find a more straightforward solution.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •