I mistakenly defined the method signature as
abstract static public function mapAttributeKeys(array $attributes)
It works properly, but while I'm refactoring the code, I see it is not looks well and it should be as following according to my habit.
abstract public static function mapAttributeKeys(array $attributes)
I little surprised how these two works. I was thinking the above syntax is a wrong syntax.
So these two are working. Is there any reason why the definition is not stricted ? Or something like a pattern match here ?
My actual aim is to learn why these flexibility is exist ? Is there any special approach or implementation trick exist ?
Updated :
I saw https://stackoverflow.com/a/10740068/1147648 this explanation really meaningful.
An abstract function will never be static, in any kind of language
if it is true, why there is implementation exist ?
Even in symfony validator loader.
https://github.com/symfony/validator/blob/master/Tests/Mapping/Loader/AbstractStaticMethodLoader.php
abstract, public and static are all modifier keywords for a function definition. There's no specific order in which they need to be stated, they're all of equivalent importance and do not rely on or interact with one another in any way.
A big, blue, round ball is the same as a blue, round, big ball.
An abstract function will never be static, in any kind of language
Jein.
The use of abstract is to force a subclass to implement a particular method, so the parent class/users of the parent class can rely on the method being there:
abstract class Foo {
abstract public function bar();
}
function baz(Foo $foo) {
$foo->bar();
}
baz doesn't know what specific instance of Foo it'll receive, but it can be sure it'll have a bar method.
Now, static methods can only be called on the class itself:
Foo::bar();
If you're writing this, you know what class you're calling bar on. You're not going to substitute Foo here; Foo is hardcoded, it is not a variable as in the case with $foo.* So... you already know what you're getting and don't need some abstract base class to enforce some interface for you.
* This is true even if you use a string variable to dynamically change the class name. The point is that you can't type hint against that, so you're on your own. Class interfaces, which includes abstract methods, only become useful and interesting with type hinting, which can only be done with object instances.
It's possible to enforce static methods to be defined on child classes, it just usually doesn't make a whole lot of practical sense.
Related
Consider the following code:
abstract class ExampleClass
{
public static function regularStaticFunction()
{
return static::abstractStaticFunction();
}
abstract protected static function abstractStaticFunction();
}
ExampleClass::regularStaticFunction();
The PhpStorm IDE puts a warning on the declaration of abstractStaticFunction that reads:
PHP Strict Standards: Static function 'abstractStaticFunction' should not be abstract.
Static function should not be abstract.
However, PHP continues program execution when parsing this class and outputs the following:
PHP Strict standards: Static function ExampleClass::abstractStaticFunction() should not be abstract in php shell code on line 7
It seems to me that because PHP allows static function calls on abstract classes, defining an abstract static function on an abstract class should not be possible.
Why are abstract static functions allowed in PHP by the interpreter, when they are nonsensical?
This is good explanation from this answer by Mark Amery:
PHP bug report 53081, called
for the warning to be dropped since the addition of the
static::foo() construct had made abstract static methods reasonable
and useful. Rasmus Lerdorf (creator of PHP) starts off by labelling
the request as bogus and goes through a long chain of bad reasoning to
try to justify the warning. Then, finally, this exchange takes place:
Giorgio
i know, but:
abstract class cA
{
//static function A(){self::B();} error, undefined method
static function A(){static::B();} // good
abstract static function B();
}
class cB extends cA
{
static function B(){echo "ok";}
}
cB::A();
Rasmus
Right, that is exactly how it should work.
Giorgio
but it is not allowed :(
Rasmus
What's not allowed?
abstract class cA {
static function A(){static::B();}
abstract static function B();
}
class cB extends cA {
static function B(){echo "ok";}
}
cB::A();
This works fine. You obviously can't call self::B(), but static::B()
is fine.
The claim by Rasmus that the code in his example "works fine" is
false; as you know, it throws a strict mode warning. I guess he was
testing without strict mode turned on. Regardless, a confused Rasmus
left the request erroneously closed as "bogus".
And that's why the warning is still in the language. This may not be
an entirely satisfying explanation - you probably came here hoping
there was a rational justification of the warning. Unfortunately, in
the real world, sometimes choices are born from mundane mistakes and
bad reasoning rather than from rational decision-making. This is
simply one of those times.
Luckily, the estimable Nikita Popov has removed the warning from the
language in PHP 7 as part of PHP RFC: Reclassify E_STRICT
notices. Ultimately,
sanity has prevailed, and once PHP 7 is released we can all happily
use abstract static without receiving this silly warning.
Abstract static functions aren't nonsensical! In fact, they enable some designs that are, to my sensibilities, simpler and cleaner than what I'd have to resort to in a language that doesn't have them, like Java or C#.
Let's take an example. Suppose I'm writing some sort of mundane enterprisey business application that needs to synchronise some business objects between two APIs. These APIs have object models that can be mapped to each other, but use different names, and different serialisation formats.
In PHP, thanks to abstract static methods, I can define an abstract base class for these business object types that looks like this...
abstract class ApiObject {
/** The REST resource URL for this object type in the Foo API. */
abstract static function fooApiResourceUrl();
/** The REST resource URL for this object type in the Bar API. */
abstract static function barApiResourceUrl();
/** Given an XML response from the Foo API representing an object of this
type, construct an instance. */
abstract static function fromFooXml($xml);
/** Given a JSON response from the Bar API representing an object of this
type, construct an instance. */
abstract static function fromBarJson($json);
/** Serialize this object in the XML format that the Foo API understands */
abstract function toFooXml();
/** Serialize this object as JSON that the Bar API understands */
abstract function toBarJson();
}
... and then every concrete subclass I create will be guaranteed to provide all the information needed to fetch it from either of the two APIs and deserialise it, or to serialize it and send it to either API. Then, later, I can write some code like this:
// Ensure that all instances of these types that exist in the Foo API also
// exist in the Bar API:
$classesToSync = ['Widget', 'Frobnicator', 'Lead', 'Invoice'];
foreach ($classesToSync as $apiObjectClass) {
$fooObjXmls = httpGetRequest($apiObjectClass::fooApiResourceUrl());
foreach ($fooObjXmls as $fooObjXml) {
$fooObj = $apiObjectClass::fromFooXml($fooObjXml);
$json = $fooObj->toBarJson();
httpPutRequest($apiObjectClass::barApiResourceUrl(), $json);
}
}
Do I strictly need abstract static methods to write the program above? No; there are other patterns I could've used, like having every model class be paired with a corresponding factory class that is responsible for instantiating it from its JSON or XML representations. But such a design is more complicated than the one I've shown above.
The answer to why they're allowed, then, is simply that they are useful, since they enable some nice, simple patterns that wouldn't be possible without them. Of course, there are also arguments against them existing, one of which was given in the question - that it's ugly to expose abstract static methods on a class given that static methods on an abstract class are callable. I don't find such considerations particularly persuasive, but even if you do, there is still a tradeoff between them and the utility that abstract static methods provide, and the PHP maintainers have presumably weighed them and opted for the side of letting abstract static methods exist.
With late static binding in PHP v5.3, one can usefully declare static methods in interfaces; with traits in PHP v5.4, methods can be either static or abstract but not both. This appears to be illogical and inconsistent.
In particular, suppose one has an interface for which a trait provides all implementation, except for a static method; unless that method is declared in the trait, static analysers balk at any references thereto from within the trait. But providing a concrete implementation within the trait no longer forces implementing/using classes to provide their own implementation—which is dangerous; abstract static would be ideal, but is not allowed.
What is the explanation for this contradiction? How would you recommend resolving this problem?
interface MyInterface
{
public static function getSetting();
public function doSomethingWithSetting();
}
trait MyTrait
{
public abstract static function getSetting(); // I want this...
public function doSomethingWithSetting() {
$setting = static::getSetting(); // ...so that I can do this
/* ... */
}
}
class MyClass implements MyInterface
{
use MyTrait;
public static function getSetting() { return /* ... */ }
}
TL;DR: As of PHP 7, you can. Before then, you could define abstract static on trait, but internals deemed it bad practice.
Strictly, abstract means sub-class must implement, and static means code for this specific class only. Taken together, abstract static means "sub-class must implement code for this specific class only". Totally orthogonal concepts.
But... PHP 5.3+ supports static inheritance thanks to LSB. So we actually open that definition up a bit: self takes the former definition of static, while static becomes "code for this specific class or any of its sub-classes". The new definition of abstract static is "sub-class must implement code for this specific class or any of its sub-classes". This can lead some folks, who think of static in the strict sense, to confusion. See for example bug #53081.
What makes trait so special to elicit this warning? Well, take a look at the engine code that implements the notice:
if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) {
zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? ZSTR_VAL(scope->name) : "", scope ? "::" : "", ptr->fname);
}
That code says the only place an abstract static is allowed is within an interface. It's not unique to traits, it's unique to the definition of abstract static. Why? Well, notice there's a slight corner case in our definition:
sub-class must implement code for this specific class or any of its sub-classes
With this code:
abstract class Foo {
abstract public static function get();
}
That definition means I should be able to call Foo::get. After all Foo is a class (see that keyword "class" there) and in the strict definition, get is meant to be implemented in that class Foo. But clearly that makes no sense, because well, we're back to the orthogonality of strict static.
If you try it in PHP, you get the only rationale response possible:
Cannot call abstract method Foo::get()
So because PHP added static inheritance, it has to deal with these corner cases. Such is the nature of features. Some other languages (C#, Java, etc.) don't have this problem, because they adopt the strict definition and simply don't allow abstract static. To get rid of this corner case, and simplify the engine, we may enforce this "abstract static only in interface" rule in the future. Hence, E_STRICT.
I would use a service delegate to solve the problem:
I have common method I want to use in several classes. This common method relies on a static method that must be defined externally to the common code.
trait MyTrait
{
public function doSomethingWithSetting() {
$service = new MyService($this);
return $service->doSomethingWithSetting();
}
}
class MyService
{
public function __construct(MyInterface $object) {
$this->object = $object;
}
public function doSomethingWithSetting() {
$setting = $this->object->getSetting();
return $setting;
}
}
Feels a bit Rube Goldberg though. Probably would look at the motivation for statics and consider refactoring them out.
PHP allows use of static member functions and variables, since 5.3 including late static bindings:
class StaticClass {
public static $staticVar;
...
}
$o = new StaticClass();
Currently, there are various options to access those static members:
$o->staticVar; // as instance variable/ function
$o::staticVar; // as class variable/ function
Other options exist for accessing members from inside the class:
self::$staticVar; // explicitly showing static usage of variable/ function
static::$staticVar; // allowing late static binding
Restructuring some existing classes that make some use of static members I've asked myself if there are best practices for working with static members in PHP?
Well, obviously, they all do different things.
$o->staticVar
This is invalid, since you cannot/should not access static properties with the instance property syntax.
StaticClass::$staticVar
This very plainly accesses a specific static variable on a very specific class.
$o::$staticVar
This accesses the static variable on the class that $o is an instance of. It's mostly used as a shorthand for the previous method and is equivalent in all respects. Obviously though, which class is used exactly depends on what class $o is an instance of.
self::$staticVar
This can be used only inside a class, and will always refer to the class that it's written in. It's a good idea to use this inside a class instead of StaticClass::$staticVar if the class refers to itself, since you don't need to worry about anything if you change the class name later. E.g.:
class Foo {
protected static $bar = 42;
public function baz() {
self::$bar; // good
Foo::$bar // the same, but should be avoided because it repeats the class name
}
}
static::$staticVar
This can also only be used inside a class and is basically the same as self above, but resolves with late static binding and may hence refer to a child class.
What the "best practice" is is debatable. I'd say you should always be as specific as necessary, but no more. $o::$staticVar and static::$staticVar both allow the class to vary through child classes, while self::$staticVar and StaticClass::$staticVar do not. Following the open/closed principle, it's a good idea to use the former, more variable method to allow for extensions.
Properties, both static and non-static, should also not be public to not break encapsulation.
Also see How Not To Kill Your Testability Using Statics.
First of all, don't use $this->staticVar. I am unsure when this changed (I believe PHP 5.4), but in recent versions it is no longer possible to retrieve static variables this way.
As for using late static binding, don't use it if you don't need it. The reason to use it would be if you plan to use inheritance and expect to change the value of the static variable in a derived class.
According to the PHP manual, a class like this:
abstract class Example {}
cannot be instantiated. If I need a class without instance, e.g. for a registry pattern:
class Registry {}
// and later:
echo Registry::$someValue;
would it be considered good style to simply declare the class as abstract? If not, what are the advantages of hiding the constructor as protected method compared to an abstract class?
Rationale for asking: As far as I see it, it could a bit of feature abuse, since the manual refers to abstract classes more as like blueprints for later classes with instantiation possibility.
Update: First of all, thanks for all the answers! But many answers sound quite alike: 'You cannot instantiate an abstract class, but for a registry, why not using a singleton pattern?'
Unfortunately, that was more or less exactly a repeat of my question. What is the advantage of using a singleton pattern (a.k.a. hiding __construct()) compared to just declaring it abstract and not having to worry about that? (Like, e.g., it is a strong connotation between developers, that abstract classes are not actually used or so.)
If your class is not meant to define some super-type, it should not be declared as abstract, I'd say.
In your case, I would rather go with a class :
That defines __construct and __clone as private methods
so the class cannot be instanciated from outside
And, this way, your class could create an instance of itself
See the Singleton design pattern, about that, btw
Now, why use a Singleton, and not only static methods ? I suppose that, at least a couple of reasons can be valid :
Using a singleton means using an instance of the class ; makes it easier to transform a non-singleton class to a singleton one : only have to make __construct and __clone private, and add some getInstance method.
Using a singleton also means you have access to everything you can use with a normal instance : $this, properties, ...
Oh, a third one (not sure about that, but might have its importance) : with PHP < 5.3, you have less possibilities with static methods/data :
__callStatic has only been introduced in PHP 5.3
There is no __getStatic, __setStatic, ...
Same for a couple of other Magic methods !
Late Static Binding has only been added with PHP 5.3 ; and not having it often makes it harder, when working with static methods/classes ; especially when using inheritance.
This being said, yes, some code like this :
abstract class MyClass {
protected static $data;
public static function setA($a) {
self::$data['a'] = $a;
}
public static function getA() {
return self::$data['a'];
}
}
MyClass::setA(20);
var_dump(MyClass::getA());
Will work... But it doesn't feel quite natural... and this is a very simple example (see what I said earlier with Late Static Binding, and magic methods).
What you describe is permitted by the PHP language, but it's not the intended usage of an abstract class. I wouldn't use static methods of an abstract class.
Here's the downside of doing that: Another developer could extend your abstract class and then instantiate an object, which is what you want to avoid. Example:
class MyRegistry extends AbstractRegistry { }
$reg = new MyRegistry();
True, you only need to worry about this if you're handing off your abstract class to another developer who won't comply with your intended usage, but that's why you would make the class a singleton too. An uncooperative developer can override a private constructor:
class Registry
{
private function __construct() { }
}
class MyRegistry extends Registry
{
public function __construct() { } // change private to public
}
If you were using this class yourself, you would simply remember not to instantiate the class. Then you wouldn't need either mechanism to prevent it. So since you're designing this to be used by others, you need some way to prevent those people from circumventing your intended usage.
So I offer these two possible alternatives:
Stick with the singleton pattern and make sure the constructor is also final so no one can extend your class and change the constructor to non-private:
class Registry
{
private final function __construct() {
}
}
Make your Registry support both static and object usage:
class Registry
{
protected static $reg = null;
public static function getInstance() {
if (self::$reg === null) {
self::$reg = new Registry();
}
return self::$reg;
}
}
Then you can call Registry::getInstance() statically, or you can call new Registry() if you want an object instance.
Then you can do nifty things like store a new registry instance inside your global registry! :-)
I implemented this as part of Zend Framework, in Zend_Registry
As other guys said, you cannot instantiate an abstract class. You could use static methods in your class to prevent instantiating, but I'm not really a fan of doing so unless I have a proper reason.
I might be little bit off-topic now, but in your example you said you wanted this for Registry pattern class. What is the reason you don't want to instantiate it? Wouldn't it better to create an instance of Registry for each registry you want to use?
Something like:
class Registry {
private $_objects = array( );
public function set( $name, $object ) {
$this->_objects[ $name ] = $object;
}
public function get( $name ) {
return $this->_objects[ $name ];
}
}
I wouldn't even use Singleton in this case.
Setting a class to abstract that only defines static properties/methods won't have a real effect. You can extend the class, instantiate it, and call a method on it and it would change the static class properties. Obviously very confusing.
Abstract is also misleading. Abstract is ment to define an class that implements some functionality, but needs more behaviour (added via inheritance) to function properly. On top of that it's usually a feature that shouldn't be used with static at all. You are practically inviting programmers to use it wrong.
Short answer: A private constructor would be more expressive and fail safe.
There are patterns in OO that are common and well-recognized. Using abstract in an unconventional way may cause confusion (sorry, my some examples are in Java instead of PHP):
abstract class - a class meant to conceptualize a common ancestor, but of which actual instances are not meant to exist (e.g. shape is an abstract superclass for rectangle and triangle).
Commonly implemented by:
use abstract modifier on class to prevent direct instantiation, but allow deriving from the class
utility class - a class that does not represent an object in the solution space, but rather is a collection of useful static operations/methods, e.g. Math class in Java.
Commonly implemented by:
make class non-derivable, e.g. Java uses the final modifier on class, and
prevent direct instantiation - provide no constructors and hide or disable any implicit or default constructors (and copy constructors)
singleton class - a class that does represent an object in the solution space, but whose instantiation is controlled or limited, often to insure there is only one instance.
Commonly implemented by:
make class non-derivable, e.g. Java uses the final modifier on class, and
prevent direct instantiation - provide no constructors and hide or disable any implicit or default constructors (and copy constructors), and
provide a specific means to acquire an instance - a static method (often getInstance()) that returns the only instance or one of the limited number of instances
abstract really is meant to indicate a "blueprint", as you call it, for class inheritance.
Registries generally follow a singleton pattern, which means they it would instantiate itself in a private variable. Defining it as abstract would prevent this from working.
I wouldnt use an abstract class. Id use something more akin to a singleton with a protected/private constructor as you suggest. There should be very few static properties other than $instance which is the actual registry instance. Recently ive become a fan of Zend Frameworks typical pattern which is something like this:
class MyRegistry {
protected static $instance = null;
public function __construct($options = null)
{
}
public static function setInstance(MyRegistry $instance)
{
self::$instance = $instance;
}
public static function getInstance()
{
if(null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
}
This way you get a singleton essentially but you can inject a configured instance to use. This is handy for testing purposes and inheritance.
The purpose of an abstract class is to define methods that are 1) meaningful to other classes and 2) not meaningful when not in the context of one of those classes.
To paraphase some of the php docs, imagine you are connecting to a database. Connecting to a database doesn't make much sense unless you have a particular kind of database to connect to. Yet connecting is something you will want to do regardless of the kind of database. Therefore, connecting can be defined in an abstract database class and inherited, and made meaningful by, say, a MYSQL class.
From your requirements, it sounds like you don't intend to do this but instead simply require a class without an instance. Whilst you could use an abstract class to enforce this behaviour, this seems hacky to me because it abuses the purpose of abstract classes. If I encounter an abstract class, I should be able to reasonably expect that this will have some abstract methods, for example, but your class will have none.
Therefore, a singleton seems like a better option.
However, if the reason you wish to have a class without an instance is simply so that you can call it anywhere then why do you even have a class at all? Why not just load every variable as a global and then you can just call it directly rather than through the class?
I think the best way to do this is to instantiate the class and then pass it around with dependency injection. If you are too lazy to do that (and fair enough if you are! Its your code, not mine.) then don't bother with the class at all.
UPDATE: It seems like you are conflicted between 2 needs: The need to do things quickly and the need to do things the right way. If you don't care about carrying a ton of global variables for the sake of saving yourself time, you will assumedly prefer using abstract over a singleton because it involves less typing. Pick which need is more important to you and stick with it.
The right way here is definitely not to use a Singleton or an abstract class and instead use dependency injection. The fast way is to have a ton of globals or an abstract class.
From my understanding, a class without instance is something you shouldn't be using in an OOP program, because the whole (and sole) purpose of classes is to serve as blueprints for new objects. The only difference between Registry::$someValue and $GLOBALS['Registry_someValue'] is that the former looks 'fancier', but neither way is really object-oriented.
So, to answer your question, you don't want a "singleton class", you want a singleton object, optionally equipped with a factory method:
class Registry
{
static $obj = null;
protected function __construct() {
...
}
static function object() {
return self::$obj ? self::$obj : self::$obj = new self;
}
}
...
Registry::object()->someValue;
Clearly abstract won't work here.
I would say it's a matter of coding habbits. When you think of an abstract class it is usually something you need to subclass in order to use. So declaring your class abstract is counter-intuitive.
Other than that is it just a matter of using self::$somevar in your methods if you make it abstract, rather than $this->somevar if you implement it as a singleton.
I need to clear some OOPS concepts in PHP.
Which is faster $this->method(); or self:method();
I know the concept of static keyword but can you please post the actual Use of it. Since it can not be accessed by the instance, but is there ant benefit for that?
what is factory? How can i use it?
What is singleton? How can i use that?
What is late static binding?
http://www.php.net/manual/en/oop5.intro.php
I have gone through below link but I am not getting clear with it.
1) Which is faster $this->method(); or self:method();
I set up a simple loop which calls the same method 1,000,000 times using both methods and the results are pretty much equal (in reality -> was slightly faster but by an extremely short margin)
2) I know the concept of static keyword but can you please post the actual Use of it. Since it can not be accessed by the instance, but is there ant benefit for that?
What do you mean not accessed by the instance?
public static $x;
public static function mymethod() {};
can be accessed through self::$x and self::mymethod().
There are multiple uses of static members, none of them very nice. They can be used to create singleton objects, the can be used to invoke class methods without needing to instantiate the class (for something like a bootstrap object)
3) what is factory? How can i use it?
Factories are objects used to abstract code needed to instantiate objects of a similar type. For example if you have a website which uses a hierarchy of users, each user level might have its own class. Fundamentally all the user classes will be created in the same way but there may be one or two class specific actions required.
A factory object would contain all this instantiation code and offer a simple interface to the developer. So you could use $oFactory->createUser() and $oFactory->createManager() instead of repeating yourself in multiple areas of your code.
4) What is singleton? How can i use that?
A singleton is a class that can have one and only one instance at any one time. The basic idea is that you would use a static method and a static variable to check if the object has already been instantiated.
You would use a singleton where it is important to only have one instance of a class, for example a security model may be a singleton since you want to make sure that there is only one place in your code responsible for authenticating users, a database abstraction could be a singleton if you only require one db connection (it wouldn't make sense to keep connecting to the same server and the same database for each query)
Pre-PHP5.3 singletons have some fundamental flaws since the absence of late static binding means that you can't easily extend a base singleton class.
5) What is late static binding?
Late static binding is a delay in class resolution for static methods to improve their use in OO (derived classes in particular). LSB allows self:: or __CLASS__ to resolve to the current class now instead of the class that they are defined in.
For example in earlier versions of PHP....
class parentClass {
public static function someMethod() {
echo( __CLASS__ );
}
}
class childClass extends parentClass {
}
$oObject = new childClass();
$oObject::someMethod();
would output parentClass to the browser, using LSB childClass would be output.
This is useful for many things including singletons, since the class is resolved properly it is now possible to define a singleton base class and have other objects extend it with expected results.
2) Static Key word: Unlike the methods
and data members used in OOPS where
the scope is decided by access
specifiers, the static
methods/attributes are available as a
part of the class. So it is available
to all the instance defined for the
class. To implement static keyword
functionality to the attributes or the
methods will have to be prefix with
“static” keyword. To assign values to
static variables you need to use scope
resolution operator(::) along with the
class name.
example:
< ?
class ClassName
{
static private $staticvariable; //Defining Static Variable
function __construct($value)
{
if($value != "")
{
ClassName::$staticvariable = $value; //Accessing Static Variable
}
$this->getStaticData();
}
public function getStaticData()
{
echo ClassName::$staticvariable; //Accessing Static Variable
}
}
$a = new ClassName("12");
$a = new ClassName("23");
$a = new ClassName("");
?>
Output:
12
23
23
Explanation:
* Here i have declared static variable $staticvariable
* In the constructor i am checking and value and then assigning the value
to the static variable
* Finally the getStaticData() method will output the static variable
content
1) Which is faster $this->method(); or self:method();
Answer: "self" (not $self) refers to
the type of class, where as $this
refers to the current instance of the
class. "self" is for use in static
member functions to allow you to
access static member variables. $this
is used in non-static member
functions, and is a reference to the
instance of the class on which the
member function was called.
Because "this" is an object, you use
it like: $this->member Because "self"
is not an object, it's basically a
type that automatically refers to the
current class, you use it like:
self::member
What is singleton? How can i use that? php
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application
Example:
final class Singleton
{
protected static $_instance;
private function __construct() # we don't permit an explicit call of the constructor! (like $v = new Singleton())
{ }
private function __clone() # we don't permit cloning the singleton (like $x = clone $v)
{ }
public static function getInstance()
{
if( self::$_instance === NULL ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
$instance = Singleton::getInstance();
5) What is late static binding?
Refer: Late Static Binding
What Is Factory?
refer Design Pattern
I have gone through below link but I
am not getting clear with it.
The official documentation is rich and comprehensive but some users find it hard to understand. If you are unable to grasp that, I would suggest you to go through this excellent tutorial at phpro.org (a great great resource on php topics):
Object Oriented Programming with PHP
The tutorial has been written in simple language with good real world examples, very helpful to those having problem in understanding the OOP concepts.
You are asking a pretty general question. Those are really basic concepts, so you should try to research a bit further, using also general OOP tutorials and reference.
Just to provide some hints: most of your question refer to the concept of "static". You need to understand the difference between a Class and an Instance of a class. This is the key concept.
A Class is the blueprint to create an instance. You have only one Class, but multiple Instances of it. To create an instance you use the "new" keyword, and give a name to the instance ($x = new A()); But you can have methods and fields which do not require a class instance to be run or accessed. The Class holds them, they are above any instance, they can not access any properties or methods which are not static themselves. They are useful because they can hold data and functions which are global (if you have a static variable, it'll be the same across the entire execution, wherever it is called).
I would strongly recommend you to read a couple a book on the subject. I would personally recommend PHP Object-Oriented Solutions by David Powers. This is in my opinion the best introduction to Object-Oriented coding in PHP for newcomers. You need the core knowledge before you can deploy programming patterns efficiently.
If you are really looking to understand design patterns, i would recommend Design Patterns by Christoffer G. Lasater. I've struggled to understand some of these patterns myself, and he explains them in a reasonable understandable way for the average programmer. It is written for Java, but the differences are not really that big.