Simple Talk about PHP deferred static binding _php instance

Source: Internet
Author: User

Working with scenes

First look at the following code:

Abstract class Base {
  //do sth
}
class AClass extends base{public
  static function create () {return
    n EW AClass ();
  }
Class Bclass extends base{public
  static function create () {return
    new Bclass ();
  }
}
Var_dump (Aclass::create ());
Var_dump (Bclass::create ());

Output:

Object (aclass) #1 (0) {} object (Bclass) #1 (0) {}

The above AClass and bclass inherit from the base abstract class, but the static method of Create () is implemented at the same time in two subclasses. Following OOP, this repetitive code should be implemented in the parent class of base.

Improved code

Abstract class Base {public
  static function create () {return
    new self ();
  } 
}
Class AClass extends base{
}
class Bclass extends base{
}
var_dump (Aclass::create ());
Var_dump (Bclass::create ());

Now that the code seems to have met our previous idea of putting the Create () method together in the parent class, let's run the next to see what happens.

Cannot instantiate abstract class base in ...

Unfortunately, the code does not seem to run as we expected, and self () in the parent class is parsed into the base parent class, not inheriting from his subclass. So in order to solve this problem, the concept of delayed static binding is introduced in php5.3.

Delay Static binding

Abstract class Base {public
  static function create () {return
    new static ();
  } 
}
Class AClass extends base{
}
class Bclass extends base{
}
var_dump (Aclass::create ());
Var_dump (Bclass::create ());

This code is almost identical to the previous one, except that the self is replaced with the static keyword, static resolves to subclasses, not the parent class, which solves the problem that is encountered above, which is the delayed static binding of PHP.

Finally, run the code and get the results you want.

Object (aclass) #1 (0) {} object (Bclass) #1 (0) {}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.