clarified behavior of property access vs. method call (fixes #49515)

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@337758 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Christoph Michael Becker 2015-09-06 15:06:02 +00:00
parent 4aac5d83bd
commit 727d059758

View file

@ -220,6 +220,75 @@ var_dump($obj4 instanceof Child);
bool(true)
bool(true)
bool(true)
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.basic.properties-methods">
<title>Properties and methods</title>
<para>
Class properties and methods live in separate "namespaces", so it is
possible to have a property and a method with the same name. Reffering to
both a property and a method has the same notation, and whether a property
will be accessed or a method will be called, solely depends on the context,
i.e. whether the usage is a variable access or a function call.
</para>
<example>
<title>Property access vs. method call</title>
<programlisting role="php">
<![CDATA[
class Foo
{
public $bar = 'property';
public function bar() {
return 'method';
}
}
$obj = new Foo();
echo $obj->bar, PHP_EOL, $obj->bar(), PHP_EOL;
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
property
method
]]>
</screen>
</example>
<para>
That means that calling an <link linkend="functions.anonymous">anonymous
function</link> which has been assigned to a property is not directly
possible. Instead the property has to be assigned to a variable first, for
instance.
</para>
<example>
<title>Calling an anonymous function stored in a property</title>
<programlisting role="php">
<![CDATA[
class Foo
{
public $bar;
public function __construct() {
$this->bar = function() {
return 42;
};
}
}
$obj = new Foo();
$func = $obj->bar;
echo $func(), PHP_EOL;
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
42
]]>
</screen>
</example>