note 88665 added to language.oop5.basic
| From: | ialsoagree at osu1 dot php dot net | Date: | Tue, 03 Feb 2009 00:23:32 +0000 |
| Subject: | note 88665 added to language.oop5.basic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-150131@lists.php.net to get a copy of this message | ||
I think it's worth mentioning that if you define a function inside of an object method, that
function cannot refer to "$this" - doing so will result in PHP reporting a fatal error:
Fatal error: Using $this when not in object context
<?php
class MyClass {
public $message = 'Hello';
public function MyClassFunction() {
function InnerFunction() {
echo $this->message; // Reports a fatal error
}
innerFunction();
}
}
$class = new MyClass;
$class->MyClassFunction();
?>
This issue cannot be solved by using the Scope Resolution Operator if you're trying to access a
variable:
<?php
class MyClass {
public $message = 'Hello';
public function MyClassFunction() {
function InnerFunction() {
echo MyClass::message; // Reports a fatal error
}
innerFunction();
}
}
$class = new MyClass;
$class->MyClassFunction();
?>
Additionally, you can NOT create a public function to access that variable:
<?php
class MyClass {
public $message = 'Hello';
public function MyClassFunction() {
function InnerFunction() {
MyClass::echoSomething();
}
innerFunction();
}
public function echoSomething() {
echo $this->message; // Reports a fatal error
}
}
$class = new MyClass;
$class->MyClassFunction();
?>
Note that in this last case, the error is generated on the line below echoSomething function
declaration, not at MyClass::echoSomething();
However, it is worth noting that when called directly, echoSomething works fine:
<?php
class MyClass {
public $message = 'Hello';
public function MyClassFunction() {
function InnerFunction() {
MyClass::echoSomething();
}
innerFunction();
}
public function echoSomething() {
echo $this->message; // Echoes 'Hello'
}
}
$class = new MyClass;
$class->echoSomething();
?>
----
Server IP: 64.71.164.2
Probable Submitter: 76.78.201.63
----
Manual Page -- http://www.php.net/manual/en/language.oop5.basic.php
Edit -- https://master.php.net/note/edit/88665
Del: integrated -- https://master.php.net/note/delete/88665/integrated
Del: useless -- https://master.php.net/note/delete/88665/useless
Del: bad code -- https://master.php.net/note/delete/88665/bad+code
Del: spam -- https://master.php.net/note/delete/88665/spam
Del: non-english -- https://master.php.net/note/delete/88665/non-english
Del: in docs -- https://master.php.net/note/delete/88665/in+docs
Del: other reasons-- https://master.php.net/note/delete/88665
Reject -- https://master.php.net/note/reject/88665
Search -- https://master.php.net/manage/user-notes.php