-
-
Save tommcfarlin/49aae6f2d029b369b2c4bdb35c7b8107 to your computer and use it in GitHub Desktop.
[PHP] Cast a PHP a Standard Class to a Specific Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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), '"'), ':') | |
)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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";} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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