How to Declare a Method Static and Nonstatic in PHP

Is it possible to declare a method static and nonstatic in PHP?

You can do this, but it's a bit tricky. You have to do it with overloading: the __call and __callStatic magic methods.

class test {
private $text;
public static function instance() {
return new test();
}

public function setText($text) {
$this->text = $text;
return $this;
}

public function sendObject() {
self::send($this->text);
}

public static function sendText($text) {
// send something
}

public function __call($name, $arguments) {
if ($name === 'send') {
call_user_func(array($this, 'sendObject'));
}
}

public static function __callStatic($name, $arguments) {
if ($name === 'send') {
call_user_func(array('test', 'sendText'), $arguments[0]);
}
}
}

This isn't an ideal solution, as it makes your code harder to follow, but it will work, provided you have PHP >= 5.3.

PHP: Static and non Static functions and Objects

Static functions, by definition, cannot and do not depend on any instance properties of the class. That is, they do not require an instance of the class to execute (and so can be executed as you've shown without first creating an instance). In some sense, this means that the function doesn't (and will never need to) depend on members or methods (public or private) of the class.

PHP static methods vs non-static methods/standard functions

To call a non-static method you need to instantiate the class (use the new keyword to create a new instance of the class).

When calling a static method you don't have to "new it up" but it won't have direct access to any of the non-static properties or methods. There are dozens of use-cases / scenarios where you might want to use one over the other.

To be quite honest it has never even crossed my mind to think about performance of using one over the other. If it got to a point where it made that much of a noticeable difference (and all major steps had been taken to increase efficiency) then I would imagine that either the maintenance costs of such a big application would outweigh the need for the increased efficiency or the logic behind the app is fairly flawed to begin with.


Examples for static and non-static

If I was going to use a class for the example in your question then I would use the static version as nothing in the method is reliant on other properties of the class and you then don't have to instantiate it:

Session::start_new_session()

vs

$session = new Session();

$session->start_new_session();

Also, static properties on a class will remember state that would have otherwise been lost if you were to use a non-static property and instantiation:

class Session
{
protected static $sessionStarted = false;

static function start_new_session()
{
if (!static::$sessionStarted) {
session_start();
static::$sessionStarted = true;
}
}
}

Then even if you did:

$session = new Session();

$hasStated = $session::sessionStarted;

$hasStarted would still be true.

You could even do something like:

class Session
{
protected static $sessionStarted = false;

public function __construct()
{
$this->startIfNotStarted();
}

function startIfNotStarted()
{
if (!static::$sessionStarted) {

session_start();

static::$sessionStarted = true;
}
}
}

This way you don't need to worry about starting the session yourself as it will be started when you instantiate the class and it will only happen once.

This approach wouldn't be suitable if you had something like a Person class though as the data would be different each time and you wouldn't want to use the same data in difference instantiations.

class Person
{
protected $firstname;

protected $lastname;

public function __construct($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
}

public function getFullname()
{
return "{$this->firstname} {$this->lastname}";
}
}
$person1 = new Person('John', 'Smith');
$person2 = new Person('Jane', 'Foster');

$person1->fullname(); // John Smith
$person2->fullname(); // Jane Foster

If you were to use static methods / properties for this class then you could only ever have one person

class Person
{
protected static $firstname;

protected static $lastname;

static function setName($firstname, $lastname)
{
static::$firstname = $firstname;
static::$lastname = $lastname;
}

static function getFullname()
{
return static::$firstname . ' ' . static::$lastname;
}
}
Person::setName('John', 'Smith');
Person::setName('Jane', 'Foster');

Person::getFullname(); //Jane Foster

The debates

You are probably going to see a lot of debates over which is better and what the best practices are when it comes to PHP (not just about static and not-static methods).

I wouldn't get bogged down with it though! If you find that one side makes more sense to you (and whatever you're building at the time) then go with that one. Standards and opinions change all the time in this community and half of the stuff that was a problem 5 years ago (or even less) will actually be non-issues today.

Take the Laravel framework as an example -- one of the (many) debates is that Facades are bad because they're static and make use of magic methods which is hard to test and debug. Facades are actually very easy to test and with the use of stack trace error reporting it isn't hard to debug at all. That's not to say their aren't caveats when it comes to testing static methods, but this is more to do with mocking/spying -- this answer goes into it in a little more detail.

That being said, if you find the majority of people are saying the same thing and there isn't really a debate for the other side, there is probably a reason e.g. don't use mysql_ functions or don't run queries inside a loops.

How to call a non-static method from a static function in a class in php

Just create an instance:

    public static function staticFun ($data) {
$instance = new ClassName($data);
echo $instance->anotherFun($data);
}

Note: you have a parameter $data for anotherFun, but you don't use it anywhere.

Static and Non-Static Calling in PHP

Here is the rule:

A static method can be used in both static method and non-static method.

A non-static method can only be used in a non-static method.

How to call non-static method from static method of same class?

You must create a new object inside the static method to access non-static methods inside that class:

class Foo {

public function fun1()
{
return 'non-static';
}

public static function fun2()
{
return (new self)->fun1();
}
}

echo Foo::fun2();

The result would be non-static

Later edit: As seen an interest in passing variables to the constructor I will post an updated version of the class:

class Foo {

private $foo;
private $bar;

public function __construct($foo, $bar)
{
$this->foo = $foo;
$this->bar = $bar;
}

public function fun1()
{
return $this->foo . ' - ' . $this->bar;
}

public static function fun2($foo, $bar)
{
return (new self($foo, $bar))->fun1();
}
}

echo Foo::fun2('foo', 'bar');

The result would be foo - bar

Laravel Static and Non-static Methods

This is being done via the magic method __callStatic which is creating a new instance of the model then calling the method on it. This particular method, where, doesn't exist on the model and is being handled by the magic method __call which is calling this method on an Eloquent Builder instance.

PHP.net Manual - OOP - Overloading __callStatic __call

Laravel - Github - Eloquent Model __callStatic

Laravel - Github - Eloquent Model __call

PHP: What if I call a static method in non-static way

As Baba already pointed out, it results in an E_STRICT depending on your configuration.

But even if that's no problem for you, I think it's worth mentioning some of the pitfalls which may result from calling static methods in a non-static way.

If you have a class hierarchy like

class A {
public static function sayHello() {
echo "Hello from A!\n";
}

public function sayHelloNonStaticWithSelf() {
return self::sayHello();
}

public function sayHelloNonStaticWithStatic() {
return static::sayHello();
}
}

class B extends A {
public static function sayHello() {
echo "Hello from B!\n";
}

public function callHelloInMultipleDifferentWays() {
A::sayHello();
B::sayHello();
$this->sayHelloNonStaticWithSelf();
$this->sayHelloNonStaticWithStatic();
$this->sayHello();
}
}

$b = new B();
$b->callHelloInMultipleDifferentWays();

This produces the following output:

Hello from A!
// A::sayHello() - obvious

Hello from B!
// B::sayHello() - obvious

Hello from A!
// $this->sayHelloNonStaticWithSelf()
// self alweays refers to the class it is used in

Hello from B!
// $this->sayHelloNonStaticWithStatic()
// static always refers to the class it is called from at runtime

Hello from B!
// $this->sayHello() - obvious

As you can see, it's easy to achieve unexpected behaviour when mixing static and non-static method calls and techniques.

Therefore, my advice also is:
Use Class::method to explicitly call the static method you mean to call.
Or even better don't use static methods at all because they make your code untestable.



Related Topics



Leave a reply



Submit