Reputation: 1617
I'm new to OOPerl, and wanted to know how I can reference an instance of a class within that class (i.e. $this
in PHP) so that I'm able to call its "private" methods
To make it more clear:
in PHP for instance:
class Foo {
public function __construct(){
}
public function doThis(){
$that = $this->doThat(); //How to reference a "private" function in perl that is defined in the same class as the calling function?
return $that;
}
private function doThat(){
return "Hi";
}
}
Upvotes: 2
Views: 214
Reputation: 126722
Perl methods are ordinary subroutines that expect the first element of their parameter array @_
to be the object on which the method is called.
An object defined as
my $object = Class->new
can then be used to call a method, like this
$object->method('p1', 'p2')
The customary name is $self
, and within the method you assign it as an ordinary variable, like this
sub method {
my $self = shift;
my ($p1, $p2) = @_;
# Do stuff with $self according to $p1 and $p2
}
Because the shift
removes the object from @_
, all that is left are the explicit parameters to the method call, which are copied to the local parameter variables.
There are ways to make inaccessible private methods in Perl, but the vast majority of code simply trusts the calling code to do the right thing.
Upvotes: 2