-
-
Save echochamber/a12ab6fb86f456bbc90b to your computer and use it in GitHub Desktop.
Copy Constructor
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
<? | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment