Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End [Solved] Arrow Operator

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #28519
    Makeshift
    Member

    Hello, I have seen some codes using this ‘->’ and I wondered how it worked.

    If someone can give me an explanation and a full example of how to use it, it would very much appreciated. =)

    #72965
    Democritus
    Member

    The arrow is an accessor in object oriented php. Here’s a simple example:

    Code:
    class MyClass {
    public $h = “Hello”;
    private $w = “World”;
    function getStatement() {
    echo $h . “, ” . $w;
    }
    }

    And now, to show you how the arrow works:

    Code:
    $myVar = new MyClass();

    So $myVar is an instance of the class above.

    Code:
    echo $myVar->h

    This is valid, because $h is a public variable in MyClass. Therefore, $myVar->h accesses the value of $h stored in this instance of MyClass.

    Code:
    echo $myVar->w

    This will cause a runtime error, because w is private. You cannot access private variables directly with the -> accessor.

    Finally,

    Code:
    $myVar->getStatement();

    will echo "Hello, World", because the method is public (public is default if not explicitly declared). MyClass has access to its own variables, so World is printed out in this case, even though we couldn’t directly access it with:

    Code:
    $myVar->w

    This answer assumes you understand object oriented concepts at least a little bit. If you don’t, head on over to http://www.php.net/manual/en/language.oop5.basic.php.

    Best of luck,
    -D

    #72974
    Makeshift
    Member

    Alright, well, I looked into it, and it seems you made a mistake in your example..

    Your function was like this:

    Code:
    function getStatement() {
    echo $h . “, ” . $w;
    }

    But in order for it to use the variables you would have to use this:

    Code:
    function getStatement() {
    echo $this->h . “, ” . $this->w;
    }

    But thank you for the example, it was very helpful.

    #72977
    Democritus
    Member

    Good catch! I wrote it on the fly, and didn’t check it. Thanks for the correction.

    I most likely made this error as I am working in Java a lot these days, which doesn’t require a this to access local variables.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘Back End’ is closed to new topics and replies.