Reputation: 10828
I am trying to figure out what does bless
do in perl - after reading their documentation - I am not very clear. Correct me if I am wrong, it allow to create properties in the class or object?
Someone coded this block of code
package Main::Call;
sub new
{
my ($class, $call) = @_;
my $self = $call;
bless($self, $class);
return $self;
}
So for example:
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;
}
I am trying to convert this to PHP.
So I am assuming it would be like this?
class Call {
public function __construct($arr) {
foreach($arr as $key => $value)
{
$this->$value = '';
}
}
public function __set($key, $value) {
$this->$key = $value;
}
}
Upvotes: 2
Views: 645
Reputation: 57600
Perl has an unusual object model: An object is a reference that was “blessed” into a class. The bless
just annotates the reference so that methods can be called upon the reference.
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" }
But usually references are only blessed inside the class'es constructor.
Perl does not dictate how an object should store its data. The most common method is to use a hash reference. This new
is similar to your PHP __construct
:
sub new {
my ($class, %init) = @_;
return bless \%init => $class;
}
which could be called like Foo->new(key => $value, ...)
.
What your Perl new
does is rather unusual: It blesses the given argument into the appropriate class. This assumes that the $call
is already a reference. If the $call
was already blessed into some package, then it is re-blessed into this $class
.
The most sane way to translate that to PHP is to stuff the $call
into an instance's property, roughly like you did.
Upvotes: 2
Reputation: 111219
The bless
function associates a class with a reference. That is, what ever you would pass to the new
function would become an object of the Main::Call
class, as long as it's a reference type. You can pass in a list reference, and it becomes an object. You can pass in a scalar reference, and it becomes an object.
There is no way to do exactly the same thing in PHP, but your attempt comes close to emulating the case when you pass a hash reference to new
.
Upvotes: 2