- This topic is empty.
-
AuthorPosts
-
March 24, 2010 at 11:39 pm #28519
Makeshift
MemberHello, 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 #72965Democritus
MemberThe 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->hThis 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->wThis 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->wThis 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,
-DMarch 25, 2010 at 10:17 pm #72974Makeshift
MemberAlright, 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 #72977Democritus
MemberGood 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.
-
AuthorPosts
- The forum ‘Back End’ is closed to new topics and replies.