[英]Constructor Overloading in PHP
I have a class like this with a overloaded constructors 我有一个这样的类,有一个重载的构造函数
<?php
/*
Users Abstract Class
*/
abstract class User
{
protected $user_email;
protected $user_username;
protected $user_password;
protected $registred_date;
//Default constructor
function User()
{
}
//overloded constructor
function User($input_username,$input_email,$input_password)
{
__set($this->user_username,$input_username);
__set($this->user_email,$user_password);
__set($this->user_password,$input_password);
}
}
?>
Above code provides an error : error:Fatal error: Cannot redeclare User::User()
上面的代码提供了一个错误:
error:Fatal error: Cannot redeclare User::User()
As other languages such as C++ and Java uses the above approach to overload the constructors how to do it in PHP OOP ? 正如其他语言如C ++和Java使用上述方法来重载构造函数如何在PHP OOP中执行它?
Im using * PHP 5.3.2 in LAMP * which OOP concepts should fully supported in this version 我在LAMP *中使用* PHP 5.3.2,在这个版本中应完全支持OOP概念
PHP doesn't have overloading. PHP没有重载。 It has a series of magic methods that are described as overloading in the manual (see: http://php.net/manual/en/language.oop5.overloading.php ), but it's not what you're thinking of.
它有一系列神奇的方法,在手册中被描述为重载(参见: http : //php.net/manual/en/language.oop5.overloading.php ),但它并不是你想到的。
Also, as an aside, the correct way to write a constructor in PHP 5+ is to use the __construct method: 另外,在PHP 5+中编写构造函数的正确方法是使用__construct方法:
public function __construct(/* args */)
{
// constructor code
}
You can't overload methods based on their arguments at all. 根本不能基于参数重载方法。 in your case the answer may be as simple as my answer to a similar question here
在你的情况下,答案可能就像我在这里回答类似问题一样简单
Overloading as you know it from other languages, is not supported in PHP. PHP中不支持您从其他语言中了解的重载。 Instead, you can use
func_get_args();
相反,你可以使用
func_get_args();
and work on it. 并努力。
http://www.php.net/func_get_args http://www.php.net/func_get_args
More information about the possibilities of overloading in PHP: http://php.net/manual/en/language.oop5.overloading.php 有关PHP中重载可能性的更多信息: http : //php.net/manual/en/language.oop5.overloading.php
You could try something like this... The use case is on the GitHub gist 你可以尝试这样的东西......用例是在GitHub上
<?php
use \InvalidArgumentException;
class MyClass{
protected $myVar1;
protected $myVar2;
public function __construct($obj = null, $ignoreExtraValues = false){
if($obj){
foreach (((object)$obj) as $key => $value) {
if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
$this->$key = $value;
}else if (!$ignoreExtraValues){
throw new InvalidArgumentException(get_class($this).' does not have property '.$key);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.