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:31

-> is the used to access methods and attributes of an object. See the PHP manual on classes and objects.

查看更多
Lonely孤独者°
3楼-- · 2019-01-14 15:35

Firstly you should understand the following. In PHP and many other languages we have the following types of entites:

  • Variables
  • Arrays
  • Objects

The -> allows you to access a method or value within an object, the same way that [] allows you to access values within an array.

A class is like a box, and within that box there is a lot of items, and each item can interact with each other as they are within the same box.

For example:

class Box
{
    function firstItem()
    {

    }


    function secondItem()
    {

    }
}

The above is what we call a class. It's basically a structured piece of code that does not really do anything until it becomes an object.

The object is created by using the new keyword, which instantiates a class and creates an objects from it.

$box = new Box;

Now the above $box, which is an object created from the Box class, has methods inside, such as firstItem().

These are just like functions apart from within them we have another variable called $this and this is used to access other methods within that object.

Now to access the methods from outside the objects you have to use the operator described in your question.

$box->firstItem();

The operator -> will allow you to execute the method from the variable $box.

查看更多
何必那么认真
4楼-- · 2019-01-14 15:44

It accesses a member of the object on the left with the name on the right.

查看更多
狗以群分
5楼-- · 2019-01-14 15:44

It is how PHP handles objects. Essentially, $wp_query is an object that has methods (functions) and attributes that can be accessed through the -> characters.

PHP didn't start with objects so you see it now as sort of an afterthought. I find -> to be a messy way to handle it, compared to say Ruby, which was built with objects from the foundation.

You can find more at: http://php.net/manual/en/language.oop5.php

查看更多
6楼-- · 2019-01-14 15:44

-> is basically used to access a filed of an object. Analogioous to attributes in Java.

for eg.

class Student {
String name;
int rollno;
}

Student.name accesses the name of a given student object.

查看更多
beautiful°
7楼-- · 2019-01-14 15:51

It's like the period (.) in JavaScript and Java. It is just a simple access operator.

查看更多
登录 后发表回答