PHP 访问受保护的构造函数
我知道使用受保护的方法或构造函数非常罕见。我在 SO 和其他网站上读过有关此问题的讨论。 我的任务相当简单。我必须从我的程序访问受保护的方法/构造函数。所有属性/方法必须声明为受保护。
我的代码可以简化为这样。我基本上被要求用最简单/最简单的方法来做到这一点。我能想到的所有解决方案要么使用一些更先进的技术(“朋友”等),要么使用公共函数,这是违反规则的。
谢谢。
class one
{
protected $attribute1;
}
class two extends one
{
protected $attribute2;
protected $attribute3;
protected function __construct($arg1, $arg2, $arg3)
{
$this->attribute1= $arg1;
$this->attribute2= $arg2;
$this->attribute3= $arg3;
}
}
$object = new two(" 1", "2", "3");
I know it is very uncommon to use protected methods or constructors. I have read discussions about this on SO and other sites.
The task I've got is rather simple. I have to access protected methods/constructors from my program. All attributes/methods must be declared as protected.
My code can be reduced to this. I'm basically asked to do this with the easiest/simplest way. All solutions I can think of either use some more advanced technique ("friends" etc) or a public function, which is against the rules.
Thank you.
class one
{
protected $attribute1;
}
class two extends one
{
protected $attribute2;
protected $attribute3;
protected function __construct($arg1, $arg2, $arg3)
{
$this->attribute1= $arg1;
$this->attribute2= $arg2;
$this->attribute3= $arg3;
}
}
$object = new two(" 1", "2", "3");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
私有或受保护构造函数的目的是防止从类外部实例化类。
您可以在返回新对象的类中创建一个公共静态函数,但如果您想让构造函数受到保护或私有,则不能直接创建它。您必须将某些内容声明为公共,否则您无法使用该类。
The purpose of a private or protected constructor is to prevent the class from being instantiated from outside of the class.
You could create a public static function in the class that returns a new object, but you cannot create it directly if you want to have the constructor be protected or private. You must have something declared as public or you cannot use the class.