note 88665 deleted from language.oop5.basic by cmb

From: Date: Mon, 21 Nov 2016 18:13:22 +0000
Subject: note 88665 deleted from language.oop5.basic by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-207267@lists.php.net to get a copy of this message
Note Submitter: ialsoagree ---- 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(); ?>

« previous php.notes (#207267) next »