php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54897 Allow class methods to determine whether they're being called statically or not
Submitted: 2011-05-21 10:44 UTC Modified: 2014-03-09 23:19 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: charles dot pick at gmail dot com Assigned:
Status: Wont fix Package: Unknown/Other Function
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2011-05-21 10:44 UTC] charles dot pick at gmail dot com
Description:
------------
At the moment there is no reliable way to determine whether a function is being 
called statically or on an object directly. Sometimes it's useful to know the 
difference between e.g.
foo::createUrl();
and
$foo->createUrl();

it would be nice to have a function, called something like is_static_call() which 
could supply this information to the current method. I'm not familiar with the PHP 
internals so I don't know how difficult this is to implement, but for me it would 
be a useful feature.

Test script:
---------------
class foo {
	public function createUrl($url = null, $params = array()) {
		if ($url === null && is_static_call()) {
			$url = "list";
		}
		elseif ($url === null) {
			$url = "view";
		}
		/* do something */
	}
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-03-09 17:19 UTC] phpmpan at mpan dot pl
It is already supported by checking if `$this` is set:

class Foo {
    public function bar() {
        var_dump(isset($this));
    }
}
Foo::bar();             // Prints bool(false) 
(new Foo())->bar();     // Prints bool(true)

However calling non-static methods as stacic is not ok and will produce strict warnings.
 [2014-03-09 23:19 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2014-03-09 23:19 UTC] requinix@php.net
Indeed: a method should be called on an instance or called statically, not both.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 11:01:30 2024 UTC