- Php change class of object
- Php change class of object
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- borzilleri / function.cast.php
- An Easy Way to Cast a PHP Standard Class to a Specific Type
- Cast a PHP a Standard Class to a Specific Type
- Understanding the Code
Php change class of object
Cast a string to binary using PHP < 5.2.1
I found it tricky to check if a posted value was an integer.
is_int ( $_POST [ ‘a’ ] ); //false
is_int ( intval ( «anything» ) ); //always true
?>
A method I use for checking if a string represents an integer value.
$foo [ ‘ten’ ] = 10 ; // $foo[‘ten’] is an array holding an integer at key «ten»
$str = » $foo [ ‘ten’]» ; // throws T_ENCAPSED_AND_WHITESPACE error
$str = » $foo [ ten ] » ; // works because constants are skipped in quotes
$fst = (string) $foo [ ‘ten’ ]; // works with clear intention
?>?php
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:
$hello = ‘Hello world’ ;
print $hello ;
unset( $hello );
$hello = ‘Hello world’ ;
$hello = (unset) print $hello ;
?>
Hoorah, we lost another line!
It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that «if either operand is a float, then both operands are evaluated as floats, and the result will be a float» but could (and I think should) provide a hierarchy that indicates, for instance, «between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins» and so on (and don’t count on my example accurately capturing the true hierarchy, as I haven’t actually done the tests to figure it out). Thanks!
May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = ‘abc’; // string ‘abc’
$u=(array) $t; // array 0 => string ‘abc’ $v=(array) $u; // array 0 => string ‘abc’
Correct me if I’m wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what’s really happening:
class MyObject /**
* @param MyObject $object
* @return MyObject
*/
static public function cast ( MyObject $object ) return $object ;
>
/** Does nothing */
function f () <>
>
class X extends MyObject /** Throws exception */
function f () < throw new exception (); >
>
$x = MyObject :: cast (new X );
$x -> f (); // Your IDE tells ‘f() Does nothing’
?>
However, when you run the script, you will get an exception.
In my much of my coding I have found it necessary to type-cast between objects of different class types.
More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.
The following code is much shorter than some of the previous examples and seems to suit my purposes. It also makes use of some regular expression matching rather than string position, replacing, etc. It takes an object ($obj) of any type and casts it to an new type ($class_type). Note that the new class type must exist:
Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin’ less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
class Point protected $x , $y ;
public function __construct ( $xVal = 0 , $yVal = 0 ) $this -> x = $xVal ;
$this -> y = $yVal ;
>
public function getX () < return $this ->x ; >
public function getY () < return $this ->y ; >
>
$p = new Point ( 25 , 35 );
echo $p -> getX (); // 25
echo $p -> getY (); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax.
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it’s on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions.
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with. and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP — and just extend the Point class already.
class Point3D extends Point protected $z ; // add extra properties.
public function __construct ( $xVal = 0 , $yVal = 0 , $zVal = 0 ) parent :: __construct ( $xVal , $yVal );
$this -> z = $zVal ;
>
public function getZ () < return $this ->z ; > // add extra functions.
>
$p3d = new Point3D ( 25 , 35 , 45 ); // more data, more functions, more everything.
echo $p3d -> getX (); // 25
echo $p3d -> getY (); // 35
echo $p3d -> getZ (); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any «single lesser object» on-the-fly, and it’s way easier to do.
Re: the typecasting between classes post below. fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem. SO here’s a simple fix:
function typecast($old_object, $new_classname) if(class_exists($new_classname)) // Example serialized object segment
// O:5:»field»:9: $old_serialized_prefix = «O:».strlen(get_class($old_object));
$old_serialized_prefix .= «:\»».get_class($old_object).»\»:»;
$old_serialized_object = serialize($old_object);
$new_serialized_object = ‘O:’.strlen($new_classname).’:»‘.$new_classname . ‘»:’;
$new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
return unserialize($new_serialized_object);
>
else
return false;
>
Thanks for the previous code. Set me in the right direction to solving my typecasting problem. 😉
If you have a boolean, performing increments on it won’t do anything despite it being 1. This is a case where you have to use a cast.
I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
Checking for strings to be integers?
How about if a string is a float?
/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*(9+)\s*$/’ , $myString , $myInt );
echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes: ‘ . $myInt [ 1 ] : ‘No’ , «\n» ;
/* checks if a string is an integer with no whitespace before or after */
$isInt = preg_match ( ‘/^5+$/’ , $myString );
echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes’ : ‘No’ , «\n» ;
/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
1+(\.4+)?
with
7+\.4+
*/
/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(8+(\.6+)?)\s*$/’ , $myString , $myNum );
echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes: ‘ . $myNum [ 1 ] : ‘No’ , «\n» ;
/* checks if a string is a float with no whitespace before or after */
$isInt = preg_match ( ‘/^8+(\.2+)?$/’ , $myString );
echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;
Php change class of object
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
borzilleri / function.cast.php
This file contains 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
/** |
* Cast an object into a different class. |
* |
* Currently this only supports casting DOWN the inheritance chain, |
* that is, an object may only be cast into a class if that class |
* is a descendant of the object’s current class. |
* |
* This is mostly to avoid potentially losing data by casting across |
* incompatable classes. |
* |
* @param object $object The object to cast. |
* @param string $class The class to cast the object into. |
* @return object |
*/ |
function cast ( $ object , $ class ) |
if ( !is_object( $ object ) ) |
throw new InvalidArgumentException ( ‘$object must be an object.’ ); |
if ( !is_string( $ class ) ) |
throw new InvalidArgumentException ( ‘$class must be a string.’ ); |
if ( !class_exists( $ class ) ) |
throw new InvalidArgumentException (sprintf( ‘Unknown class: %s.’ , $ class )); |
if ( !is_subclass_of( $ class , get_class( $ object )) ) |
throw new InvalidArgumentException (sprintf( |
‘%s is not a descendant of $object class: %s.’ , |
$ class , get_class( $ object ) |
)); |
/** |
* This is a beautifully ugly hack. |
* |
* First, we serialize our object, which turns it into a string, allowing |
* us to muck about with it using standard string manipulation methods. |
* |
* Then, we use preg_replace to change it’s defined type to the class |
* we’re casting it to, and then serialize the string back into an |
* object. |
*/ |
return unserialize( |
preg_replace( |
‘/^O:\d+:»[^»]++»/’ , |
‘O:’ .strlen( $ class ). ‘:»‘ . $ class . ‘»‘ , |
serialize( $ object ) |
) |
); |
> |
?> |
An Easy Way to Cast a PHP Standard Class to a Specific Type
If you work with object-oriented PHP in WordPress and you’re building out various models that fit your web applications, the odds are that you’re going to deal with retrieving serialized versions of those models at some point during a program’s execution.
Here’s the thing, though: Sometimes, that unserialized data come back as standard PHP classes. This means that if you inspect the type (through various debugging tools), you’re going to see they are the type of stdClass.
If you’ve been properly building your models those, your code is going to have functions that the stdClass does not, and you’re going to want to call on them.
Further, you can’t simply cast them from one type to another like you can with native types (such as strings, integers, and so on). In situations like that, you need to be able to cast a PHP standard class to a specific type.
And here’s a function that will help you do just that.
Cast a PHP a Standard Class to a Specific Type
For this example, assume the following:
- I have a class that’s namespaced as Acme\Model\Product.
- It, at some point, is saved to the WordPress database but when retrieved is set as an instance of stdClass.
- I need the unserialized version of the object to be that of the Product.
To that end, I have the following function available that I drop into projects as I need it:
Sure, the function is commented with as much detail as I can provide, but there are a few things I can explain a bit further in the context of a post than I can in the context of a code comment.
Understanding the Code
First, it’s important to make sure you understand the following PHP functions (all of which are well-defined in the PHP manual):
- unserialize. Creates a PHP value from a stored representation.
- sprintf. Return a formatted string
- strlen. Get string length
- strstr. Find the first occurrence of a string.
- serialize. Generates a storable representation of a value.
So, yes, the incoming instance of the class is retrieved and then cast as the specified type but how do the above functions play a role in this? It has to do with how a class is serialized into the WordPress database.
Take for example the following string:
I know – it’s not exactly a pleasure to review, but it’s exactly how WordPress serializes an object. Further, when it’s retrieved from the database, it’s done so and then returned as a stdClass instance, not as an instance of the type it was before it was saved.
That’s where the above function comes into play. To restore it to its deal type, you’ll want to cast it as such. And to do that, you can simply do the following:
Note that I’m retrieving an object that’s been serialized to the options table. I’m not making a case as to if you should do this or not, this is for example purposes.
Secondly, note that I’m calling cast on an instance of $this so $this could be an instance of a class or it could be a method in the base class. It doesn’t matter (as long as the latter is marked as protected).
From there, you now have an instance of the class that you originally saved with all of the information available to you as it were when you first saved it.