我在perl和php中都见过这个(例如:$variable -> define something),但我以前从未真正使用过它。这个操作符的目的是什么->它是赋值还是传递参数?
谢谢
在Perl中,->
操作符意味着解引用和调用,这取决于操作符右边的内容。如果rhs为括号下标,则[...]
、{...}
或(...)
为解引用。如果是标量$some_name
或无字some_name
,则正在调用方法调用。
my $array_ref = [1, 2, 3];
say $array_ref->[2]; # prints 3
say $$array_ref[2]; # also prints 3
my $hash_ref = {a => 1, b => 2};
say $hash_ref->{b}; # prints 2
say $$hash_ref{b}; # also prints 2
my $code_ref = sub {"[@_]"};
say $code_ref->('hello'); # prints "[hello]"
say &$code_ref('hello'); # also prints "[hello]"
my $object = Some::Package->new();
$object->some_method(...); # calls 'some_method' on $object
my $method = 'foo';
$object->$method(...); # calls the 'foo' method on $object
$object->$code_ref(...); # same as $code_ref->($object, ...)
我个人更喜欢对数组和哈希使用双符号形式的解引用,并且只在调用代码引用和调用方法时使用->
。
对于perl, ->
运算符可能表示:
- 解引用数组、散列或子路由引用,请参见perldoc perlreftut
- 方法调用,参见perdoc perlobj。
哦,也许我忘了什么。
PHP
它在OOP中使用,它可以是一个方法(但当然最后会有())或一个类的属性。我不知道perl,所以我不能告诉你它是什么,但php:一些例子,希望能澄清一些事情:
在php中,我们可以这样创建一个类的对象:$object = new MyClass();
如果我们有一个名为peer的方法你可以这样调用它:
$object -> getInstance();
如果我们在同一个类中有一个属性叫做spoon你可以这样回显它:
echo $object -> instance;
这是可行的,但是你也可以在你的类中创建一个getter方法还有一个类的小例子:
class MyClass {
// property instance
private $instance;
protected __construct()
{
}
// getInstance method
protected static function getInstance()
{
return $this -> instance;
}
}
可能想看看这里http://php.net/manual/en/language.oop5.php
Perl箭头操作符主要用于从对象或类名解引用方法或变量。$obj->$a
是一个从对象$obj
访问变量$a
的例子。它也可以用来调用像$obj->$a()
这样的方法欲了解更多信息,请访问此网址:http://perldoc.perl.org/perlop.html#The-Arrow-Operator