Skip to content

Instantly share code, notes, and snippets.

@souflam
Last active March 8, 2018 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souflam/a1a3911d6c7a4911076420a8c69fee2f to your computer and use it in GitHub Desktop.
Save souflam/a1a3911d6c7a4911076420a8c69fee2f to your computer and use it in GitHub Desktop.
cast a Object to a class
<?php
class Foo {
public $item ;
function __construct($item = '') {
$this->item = $item;
}
public function getItem() {
return $this->item;
}
public function setItem($item) {
$this->item = $item;
}
}
$newFoo = new Foo('test');
$newTest = new stdClass();
//je vais attribuer la meme attribut item a cette nouvelle instance de la classe stdClass
$newTest->item = 'newTest';
echo $newFoo->getItem() . "\n";
echo $newTest->item. "\n";;
//tester si $newFoo est une instance de la class Foo
var_dump($newFoo instanceof Foo); //retrun true
//tester si $newTest est une instance de la class Foo
var_dump($newTest instanceof Foo); //retrun false
//maintenant je cast la variable $newTest
$newTest = cast('Foo', $newTest);
var_dump($newTest instanceof Foo); //return true
//maintenant il va retourner true vu que notre instance $newTest a été convertit comme instance de la class Foo
/*static **
* Class casting
*
* @param string|object $destination
* @param object $sourceObject
* @return object
*/
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->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name)) {
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
} else {
$destination->$name = $value;
}
}
return $destination;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment