Edit report at https://bugs.php.net/bug.php?id=43845&edit=1
ID: 43845
Comment by: klaussantana at gmail dot com
Reported by: ms419 at freezone dot co dot uk
Summary: Function can no longer be called both statically and
as instance method
Status: Open
Type: Feature/Change Request
Package: Feature/Change Request
PHP Version: 5.2.5
Block user comment: N
Private report: N
New Comment:
Actually, you must declare your method static. It will not produce any warning,
but you will cannot be able to use $this.
Instead, you must always use the first parameter.
So this will be like this:
<?php
class MyClass
{
static public function MyMethod()
{
$this = $Instance = func_get_arg(0);
if ( ! $this instanceof self )
{ throw new Exception('You must use this method with an Instance of
the
same class.'); }
/* ... your code here ... */
}
}
?>
Remember.. You will always need to pass the instance for your method to work
correctly.
Farewell.
Previous Comments:
------------------------------------------------------------------------
[2008-01-14 20:15:20] ms419 at freezone dot co dot uk
Description:
------------
I understand that, unlike some other languages, PHP does not support
overloading: I can't implement two functions with the same name but different
signatures. However I can simulate overloading using func_get_args() and
testing with which arguments the function was called.
Now what I want is a function which can be called either as an instance method
with no arguments, or statically with one argument: an instance of the class. I
test whether the function was called statically or not using isset($this)
However in PHP5, this produces an error:
Non-static method BaseTaxonomy::getTerms() should not be called statically in...
Like it is possible to simulate overloading in PHP without generating errors, I
wish it were possible to define a function which can be called either
statically or as an instance method, without generating errors.
Much thanks, Jack
Reproduce code:
---------------
Toy example:
class BaseTaxonomy
{
protected $terms = null;
public function getTerms()
{
if (!isset($this))
{
$args = func_get_args();
return $args[0]->terms;
}
return $this->terms;
}
}
Actual result:
--------------
Non-static method BaseTaxonomy::getTerms() should not be called statically in...
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=43845&edit=1