Skip to content

Instantly share code, notes, and snippets.

@echochamber
Created September 2, 2013 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save echochamber/a12ab6fb86f456bbc90b to your computer and use it in GitHub Desktop.
Save echochamber/a12ab6fb86f456bbc90b to your computer and use it in GitHub Desktop.
Copy Constructor
<?
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