Grow your CSS skills. Land your dream job.

[Solved] Arrow Operator

  • # March 24, 2010 at 11:39 pm

    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. =)

    # March 25, 2010 at 1:00 am

    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

    # March 25, 2010 at 10:17 pm

    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.

    # March 26, 2010 at 2:03 am

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".