我试图弄清楚 bless
在 perl 中做什么 - 在阅读他们的文档之后 - 我不是很清楚。如果我错了,请纠正我,它允许在类或对象中创建属性吗?
有人编写了这段代码
package Main::Call;
sub new
{
my ($class, $call) = @_;
my $self = $call;
bless($self, $class);
return $self;
}
例如:
if (($statement = $db->prepare($sql)) && $statement->execute())
{
while (my $rt = $statement->fetchrow_hashref())
{
my $obj = Main::Call->new($rt);
push @reserv_call_objs, $obj;
}
return \@reserv_call_objs;
}
我正在尝试将其转换为 PHP。
所以我假设它会是这样的?
class Call {
public function __construct($arr) {
foreach($arr as $key => $value)
{
$this->$value = '';
}
}
public function __set($key, $value) {
$this->$key = $value;
}
}
最佳答案
Perl 有一个不寻常的对象模型:对象是被“祝福”到类中的引用。 bless
只是对引用进行注释,以便可以在引用上调用方法。
my $data = 1;
my $ref = \$data; # the reference can be of any type
$ref->foo; # this would die: Cannot call method "foo" on unblessed reference
bless $ref => 'Foo'; # *magic*
$ref->foo; # now this works
package Foo;
sub foo { print "This works\n" }
但通常引用仅在类的构造函数内受到祝福。
Perl 没有规定对象应如何存储其数据。最常见的方法是使用哈希引用。这个 new
与 PHP __construct
类似:
sub new {
my ($class, %init) = @_;
return bless \%init => $class;
}
可以这样调用 Foo->new(key => $value, ...)
。
你的 Perl new
所做的事情相当不寻常:它将给定的参数祝福到适当的类中。这假设 $call
已经是一个引用。如果$call
已经被祝福到某个包中,那么它会被重新祝福到这个$class
中。
将其转换为 PHP 的最明智的方法是将 $call
填充到实例的属性中,大致就像您所做的那样。
关于php - Perl 'bless' 到 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874617/