note 116344 added to language.oop5.properties
| From: | Anonymous | Date: | Tue, 16 Dec 2014 09:35:16 +0000 |
| Subject: | note 116344 added to language.oop5.properties | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201202@lists.php.net to get a copy of this message | ||
In case this saves anyone any time, I spent ages working out why the following didn't work:
class MyClass
{
private $foo = FALSE;
public function __construct()
{
$this->$foo = TRUE;
echo($this->$foo);
}
}
$bar = new MyClass();
giving "Fatal error: Cannot access empty property in ...test_class.php on line 8"
The subtle change of removing the $ before accesses of $foo fixes this:
class MyClass
{
private $foo = FALSE;
public function __construct()
{
$this->foo = TRUE;
echo($this->foo);
}
}
$bar = new MyClass();
I guess because it's treating $foo like a variable in the first example, so trying to call
$this->FALSE (or something along those lines) which makes no sense. It's obvious once
you've realised, but there aren't any examples of accessing on this page that show that.
&
Do not confuse php's version of properties with properties in other languages (C++ for
example). In php, properties are the same as attributes, simple variables without functionality.
They should be called attributes, not properties.
Properties have implicit accessor and mutator functionality. I've created an abstract class
that allows implicit property functionality.
<?php
abstract class PropertyObject
{
public function __get($name)
{
if (method_exists($this, ($method = 'get_'.$name)))
{
return $this->$method();
}
else return;
}
public function __isset($name)
{
if (method_exists($this, ($method = 'isset_'.$name)))
{
return $this->$method();
}
else return;
}
public function __set($name, $value)
{
if (method_exists($this, ($method = 'set_'.$name)))
{
$this->$method($value);
}
}
public function __unset($name)
{
if (method_exists($this, ($method = 'unset_'.$name)))
{
$this->$method();
}
}
}
?>
after extending this class, you can create accessors and mutators that will be called automagically,
using php's magic methods, when the corresponding property is accessed.
----
Server IP: 72.52.91.14
Probable Submitter: 203.129.207.251
----
Manual Page -- http://php.net/manual/en/language.oop5.properties.php
Edit -- https://master.php.net/note/edit/116344
Del: integrated -- https://master.php.net/note/delete/116344/integrated
Del: useless -- https://master.php.net/note/delete/116344/useless
Del: bad code -- https://master.php.net/note/delete/116344/bad+code
Del: spam -- https://master.php.net/note/delete/116344/spam
Del: non-english -- https://master.php.net/note/delete/116344/non-english
Del: in docs -- https://master.php.net/note/delete/116344/in+docs
Del: other reasons-- https://master.php.net/note/delete/116344
Reject -- https://master.php.net/note/reject/116344
Search -- https://master.php.net/manage/user-notes.php