note 69126 deleted from function.get-object-vars by bobby
| From: | bobby@php.net | Date: | Wed, 22 Nov 2006 21:36:35 +0000 |
| Subject: | note 69126 deleted from function.get-object-vars by bobby | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-119993@lists.php.net to get a copy of this message | ||
Note Submitter: armantic101 at gmail dot com
----
I've been spoiled by OOP in C++ so I thought it was strange there was no built in copy
constructor (At least not one that I could find ..sorry, I'm still kinda new to PHP).
I was able to use get_object_vars to simulate this. Here it is if anyone else can find it usefull.
<?php
class SomeObj {
private $myVar1 = 0;
private $myVar2 = 0;
# constructor
function SomeObj($_obj = Null) {
#check just to make sure ;-)
if (get_class($_obj) == get_class($this) ) {
$arMyVars = get_object_vars($_obj);
foreach ($arMyVars as $name => $value) {
$this->$name = $value;
}
}
}
function changeVars($_var1, $_var2) {
$this->myVar1 = $_var1;
$this->myVar2 = $_var2;
}
function printVars() {
print "$this->myVar1 $this->myVar2\n";
}
}
$oldObj = new SomeObj();
$oldObj->printVars();
$oldObj->changeVars(1, 2);
$newObj = new SomeObj($oldObj);
$newObj->printVars();
?>
output:
0 0
1 2
Hope someone can find this usefull.
...now to figure out how to make multiple constrictors.