Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Object casting in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 133
    Comment on it

    Hello Reader's if you need to cast the objects in PHP then this blog is helpful to you . Here below I created a function which will cast the object and relocate the object to location as you define

      function cast($destination, $sourceObject)
        {
            if (is_string($destination)) {
                $destination = new $destination();
            }
            $sourceReflection = new ReflectionObject($sourceObject);
            $destinationReflection = new ReflectionObject($destination);
            $sourceProperties = $sourceReflection->getProperties();
            foreach ($sourceProperties as $sourceProperty) {
                $sourceProperty->setObject1ccessible(true);
                $name = $sourceProperty->getName();
                $value = $sourceProperty->getValue($sourceObject);
                if ($destinationReflection->hasProperty($name)) {
                    $propDest = $destinationReflection->getProperty($name);
                    $propDest->setObject1ccessible(true);
                    $propDest->setValue($destination,$value);
                } else {
                    $destination->$name = $value;
                }
            }
            return $destination;
        }
    

    Now the execution of the function will occur as in the following steps:-

    class Object1 
    {
      private $_MyLocation;   
    }
    
    class Object2 
    {
      public $_MyLocation;   
    }
    $a = new Object1();
    $b = new Object2();
    $MyLocation = cast('Object1',$b);
    $MyLocation = cast('Object2',$a);
    

    Now in the final result of $MyLocation both the objects will moved to the location where user will assign them in a single variable.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: