What does “->” mean/refer to in PHP? [duplicate]

2019-01-14 14:50发布

This question already has an answer here:

What does -> mean/refer to in PHP?

In the following from WordPress, I know what the if statement does, for example, but what does the -> do?

<?php if ( $wp_query->max_num_pages > 1 ) : ?>   

12条回答
虎瘦雄心在
2楼-- · 2019-01-14 15:51
<?php
class Main{
 private $name = 'My Name is Febri.<br/>';
 private function print_name(){
  echo $this -> name;
 }
}

class Descend extends Main{
 function print(){
  $this -> print_name();
 }
}

$try = new Descend;
$try -> print();
echo $try -> name;
?>

From the example above, we can not call a function which is a private print_name method. In addition, we also can not call the name variable which is set as private property.

查看更多
Deceive 欺骗
3楼-- · 2019-01-14 15:54

This is very simple to understand.

In PHP we use -> to access a method/property defined inside a class.

So in your case ($wp_query->max_num_pages), you are trying the get the value of max_num_pages which is a variable of $wp_query class.

$wp_query object information defining the current request, and then $wp_query determines what type of query it's dealing with (possibly a category archive, dated archive, feed, or search), and fetches the requested posts. It retains a lot of information on the request, which can be pulled at a later date.

查看更多
家丑人穷心不美
4楼-- · 2019-01-14 15:55

-> accesses a member of an object. So $wp_query->max_num_pages is accessing the field max_num_pages in the object $wp_query. It can be used to access either a method or a field belonging to an object, and if you're familiar with C++ or Java, it's equivalent to myObject.myField

查看更多
smile是对你的礼貌
5楼-- · 2019-01-14 15:55

Use -> to access fields, methods in an object, it is parallel to [] in array variables ($array['field'] is $object->field). In WP you'll use it on $post for example, since it is an object.

查看更多
祖国的老花朵
6楼-- · 2019-01-14 15:56

It accesses the member of the object; $obj->prop accesses the "prop" property of whatever object is in the $obj variable.

In many other programming languages, a period is used for this purpose: obj.prop or obj.method(), for example.

查看更多
混吃等死
7楼-- · 2019-01-14 15:56

$object->property is used to access the property of any object.

查看更多
登录 后发表回答