Disambiguation of method signatures for PHP "overloading"
I have a method that supports complex "overloading" by utilizing func_get_args to determine the method signature. In some situations however, the argument types are too ambiguous to make a distinction.
designGarment('my shirt', SIZES::XXL, FABRICS::COTTON);
designGarment('my dress', FABRICS::SILK, ATTIRES::PARTY);
开发者_C百科
In the example above, both method signatures resolve to STRING, INT, INT because SIZES, FABRICS and ATTIRES are classes with integer constants defined for their respective properties. I want to be able to distinguish a (STRING, SIZES, FABRICS) signature from a (STRING, FABRICS, ATTIRES) signature. Is this possible in PHP?
Use objects instead of guessing arguments:
class Garment
{
var $name;
var $size;
var $fabric;
var $attires;
}
$Garment = new Garment(...);
function designGarment($Garment);
Or use an array of key/value pairs to explicitly specify arguments and their values:
designGarment(array(
'name' => 'my dress',
'fabric' => FABRICS::SILK,
'attires' => ATTIRES::PARTY
));
Beside @Brad Christie answer there are few others:
Recomended: use arguments in constant order and null as default values for missing ones
function designGarment($name, $size = null, $fabric = null, $attire = null){ if(!is_null($size)){ } //etc } designGarment('my dress', NULL, FABRICS::SILK, ATTIRES::PARTY);
Use Object to store optional arguments
$options = new stdClass; $options->size = SIZES::XXL; function designGarment($name, $options = null){ }
Make separeate object for every type of property
function designGarment(){ foreach(func_get_args() as $arg){ if($arg instanceof Size){ } } } designGarment($name, new Size('XXL'), new Fabric('WOOL'));
Similar to above, but to have separate object for every type and value of property (not recommended, but I've seen some cases using this)
class Size{ public $size; } class SizeXXL extends Size{ public function __construct(){ $this->size = SIZES::XXL; } } designGarment($name, new SizeXXL);
精彩评论