secret
Created

Copy Constructor

  • Download Gist
CopyConstructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
 
 
<?
 
class myClass
{
//Allowed names for using __set
protected static $allowedSetValues = array(
//Member Variables
'userName',
 
//Other class dependencies
'mysqli'
);
 
//Allowed names for using __get
protected static $allowedGetMethods = array();
 
 
//An array that stores all the member variables to allow __set and __get work correctly
protected $memberVars;
 
 
protected function __construct()
{
foreach (self::$allowedSetValues as $i => $value) {
$memberVars[$value] = NULL;
}
}
 
//Just in case I want to implement constructor overloading in the future
public static function create()
{
return new className();
}
 
/**
***************
* copy
***************
* Copy constructor
* @param string $classname - Name of class. Must be a child class of oldObject, or another instance of oldObject class
* @paramobject $oldObject - The object being copied
* @return string $result - Returns
*/
public static function copy($className, $oldObject)
{
//check to see if class exists
if(!class_exists($className))
return false;
//check to see if the class $className is actually a child class of the $oldObject
// or an instance of oldObject
if( !is_subclass_of($className, get_class($oldObject) ) &&
get_class($oldObject) !== $className )
return false;
$result = new $className;
foreach (self::$allowedSetMethods as $i => $value) {
$result->memberVars[$value] = $oldObject->memberVars[$value];
}
return $result;
}
 
public function __set($name, $value)
{
if(in_array($name, self::$allowedSetValues))
{
$this->memberVars[$name] = $value;
return true;
}
else
return false;
}
 
public function __get($name)
{
if
(//if variable is actually set, and is allowed to be accessedw
in_array($name, self::$allowedGetValues) &&
in_array($name, $this->memberVars)
)
{
$this->memberVars[$name] = $value;
return true;
}
else
return false;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.