Skip to content

Instantly share code, notes, and snippets.


tommcfarlin/00-cast-class-to-type.php Secret

Last active Jan 30, 2020
What would you like to do?
[PHP] Cast a PHP a Standard Class to a Specific Type
* This function will take an instance of a PHP stdClass and attempt to cast it to
* the type of the specified $className.
* For example, we may pass 'Acme\Model\Product' as the $className.
* @param object $instance an instance of the stdClass to convert
* @param string $className the name of the class type to which we want to cals
* @return mixed a version of the incoming $instance casted as the specified className
protected function cast($instance, $className)
return unserialize(sprintf(
strstr(strstr(serialize($instance), '"'), ':')
O:17:"Acme\Model\Product":8:{s:25:"�Acme\Model\Product�number";s:3:"532";s:23:"�Acme\Model\Product�name";s:23:"Aura Bath & Spa - Matte";s:27:"�Acme\Model\Product�longName";s:56:"Aura Bath & Spa Waterborne Interior Paint - Matte Finish";s:22:"�Acme\Model\Product�url";s:37:"";s:27:"�Acme\Model\Product�shortUrl";s:9:"/aura_532";s:26:"�Acme\Model\Product�image1x";s:153:" Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_88x86.content_en_US";s:26:"�Acme\Model\Product�image2x";s:155:" Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_197x193.content_en_US";s:26:"�Acme\Model\Product�image3x";s:155:" Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_197x193.content_en_US";}
$exampleObject = get_option('acmeModelProject', null);
if (null === $exampleObject) {
$exampleObject = $this->cast($exampleObject, 'Acme\Model\Product');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.