Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin

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

Last active Jan 30, 2020
Embed
What would you like to do?
[PHP] Cast a PHP a Standard Class to a Specific Type
<?php
/**
* 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(
'O:%d:"%s"%s',
\strlen($className),
$className,
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:"http://www.benjaminmoore.com/aura_532";s:27:"�Acme\Model\Product�shortUrl";s:9:"/aura_532";s:26:"�Acme\Model\Product�image1x";s:153:"www2.benjaminmoore.com/ShowPropertyServlet?nodePath=/BEA Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_88x86.content_en_US";s:26:"�Acme\Model\Product�image2x";s:155:"www2.benjaminmoore.com/ShowPropertyServlet?nodePath=/BEA Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_197x193.content_en_US";s:26:"�Acme\Model\Product�image3x";s:155:"www2.benjaminmoore.com/ShowPropertyServlet?nodePath=/BEA Repository/imagerepository/public_site/product_images_new/IA_pri_0532//image_197x193.content_en_US";}
<?php
$exampleObject = get_option('acmeModelProject', null);
if (null === $exampleObject) {
return;
}
$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.