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.
Related
I have an abstract class like this
<?php
abstract class AbastractCreationCommand extends AbstactCommand {
protected $repository;
function handle($payload) {
$this->repository->create($payload);
}
}
class TagCreationCmd extends AbstractCreationCommand {
function __constructor() {
$this->repository = new TagRepository();
}
}
?>
Questions:
is there a way I could enforce the definition of the repository class in the subclasseses of the AbstractCreationCommand ?
Do I need to create a test for each subclass and call handle method or is another way to test all my code?
Answering number 1: You cannot enforce the creation of anything in subclasses from within your abstract class. At least not during instantiation. Everything in the subclass is optional.
However, your code in the abstract class could check whether or not the necessary objects have been defined when executing the part of the code that needs it, like this:
abstract class AbastractCreationCommand extends AbstactCommand {
protected $repository;
function handle($payload) {
if (!$this->repository instanceof TagRepository) {
throw new \InvalidArgumentException('Need a TagRepository');
}
$this->repository->create($payload);
}
}
However, is likely doing the complaining too late. And the reason may be because you are using inheritance instead of composition, or are inheriting the wrong things.
First of all, you are not doing dependency injection. Your subclass should not directly instantiate that TagRepository. This leads to problems testing your abstract class' code, as well as the subclass code, because you cannot provide a mock object instead. This severely limits the ability to test your code in isolation.
Also, the subclass cannot work without knowing very specifically how to inherit the abstract class beyond implementing any abstract functions. If both abstract and subclass come from you as the author, I would consider it to be ok to impose doing all things correctly on you. But if you expect other developers to inherit that abstract class (and your question sounds like this might be the background problem), then you shouldn't do this at all.
Abstract classes do provide some common functions to a set of subclasses through inheritance. But the same thing could be achieved if you put all the code into a non-abstract class and inject this class into independent ex-sub classes. They will call these common functions as public methods instead of private or protected, and the testing of the common code is also easier, because the methods are public.
Also note that you already have three levels of inheritance, which is nearing a uncomfortable level: AbstractCommand -> AbstractCreationCommand -> TagCreationCmd.
The problem is that everything you change in AbstractCommand has to be done with two levels of inheriting objects in mind. You cannot simply change a protected variable's name. You cannot simply add a protected (or public) variable without checking if any of the sub classes already has such a variable with the same name - unless you intend to share it.
The problems with maintaining code that is inherited is not with the classes at the end of the inheritance chain, but with these at the top. Just think about how many classes might be affected with different usage contexts: If you have AbstractCreationCommands, you will have AbstractDeletionCommands and AbstractChangeCommands and AbstractDoNothingCommands, and a plethora of concrete commands of all these kinds doing plenty of different stuff. Just imaging that on each level, you have four classes - this makes you having to maintain one base class, four inheriting classes, and four times four concrete classes - for a whopping 21 classes in total, all of them having to be tested, and likely none of them gaining any benefit from being an instanceof AbstractCommand.
Answering number 2: Yes, you have to test all subclasses - these are the ones that get instantiated and used. You should also test the abstract class' code in isolation. PHPUnit offers to instantiate an abstract class with the mock framework, so any abstract method would be mocked and could be configured. However, I always have a bad feeling when I use a mock as the real tested object because I am not really testing the pure code, but some combination of mock code and real code.
A possible way out is to create a test class that barely does anything beyond extending the abstract class, and work with this one.
1.Yes. I do the same when I need to force instantiation of some dependancies. And this way is support GRASP: Creator principle.
Another way to accomplish that with dependency injection, but this way broke Creator principle:
class TagCreationCmd extends AbstractCreationCommand {
function __constructor(TagRepositoryInterface $tagRepository) {
$this->repository = $tagRepository;
}
}
If follow 3 rules of TDD you should write test for each line of code. So the answer is yes.
Is there a way I could enforce the definition of the repository class in the subclasseses of the AbstractCreationCommand ?
I don't see the necessity tbh. If your AbstractCreationCommand needs a repo to work, add it as a constructor param. This doesn't enforce the repo to be injected because a subtype can override the constructor, but it should be abundantly clear that an AbstractCreationCommand subtype requires some sort of repo then, e.g.
abstract class AbstractCreationCommand extends AbstractCommand
{
private $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository
}
protected function getRepository(): Repository
{
return $this->repository;
}
// …
You could also use a Template Method pattern to indicate that any subtype will utilize a repo by adding an abstract getter for the repo. The subtype will have to implement that method then. It's then up to the developer to decide on the implementation:
abstract class AbstractCreationCommand extends AbstractCommand
{
public function handle()
{
$this->getRepository()->create();
}
abstract function getRepository(): Repository;
// …
If you really must enforce it at creation level, you can set the abstract type's constructor to final protected and do any subtype creation in a static factory method, e.g.
abstract class AbstractCreationCommand extends AbstractCommand
{
private $repository;
final protected function __construct(Repository $repository)
{
$this->repository = $repository;
}
// …
This now prevents direct instantiation of any subtypes via new. Trying to new a subtype, will result in PHP Fatal error.
Instead the subtype must be created like this:
class TagCreationCommand extends AbstractCreationCommand
{
private $foo;
public static function create(Repository $repository, Foo $foo)
{
$command = new static ($repository);
$command->setFoo($foo);
return $command;
}
protected function setFoo(Foo $foo)
{
$this->foo = $foo;
}
// …
Then you'd call TagCreationCommand::create(new TagRepository, new Foo); to get a new instance. Since you cannot override the constructor and have to call the parent constructor from within the static create method, you effectively enforce a Repository now to be there. I added the Foo stuff only to illustrate how you'd use additional dependencies.
As you can hopefully see, this requires quite a lot of gymnastics compared to the much more lightweight previous two approaches that will basically result in the same outcome. After all, if there is no repo, the code will fail. And since you are using tests, this will get noticed. So why bother?
Do I need to create a test for each subclass and call handle method or is another way to test all my code?
If you are overriding the handle method, you should test that behavior in a concrete test class for that subtype.
If your subtypes do not override the handle method, you can create an AbstractCreationCommandTest and put a test for the handle method in there. However, if that is the case, I wonder why you need the AbstractCreationCommand to be abstract in the first place because then it sounds like you just need a CreationCommand.
Following Yan Burtovoy's suggestion, I would go even further and actually enforce a DI container
<?php
abstract class AbastractCreationCommand extends AbstactCommand {
protected $repository;
function __constructor(\DI\Container $container) {
$this->repository = $container->get('TagRepository');
}
function handle($payload) {
$this->repository->create($payload);
}
}
You should create tests for everything that is exposed to users of your library (that would be your application).
So, if you have a subclass that relies on handle() being called then you should write a test for that. Reason being that in 6 months someone might change the inheritance or overwrite the handle() method and change the initial expected behaviour.
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.
I am reviewing some code a colleague of mine has written and I am trying to wrap my head around his design. It appears they have a class that is mostly static, but has a private constructor method. Within the class, there are methods that then construct new objects from that same class. Is this considered an 'okay' practice? Or is this kind of a wonky way of doing a class?
Here's the abstract code:
class ABC
{
static public $PROP1 = 'car';
static public $PROP2 = 'blue';
static public $PROP3 = 'apple';
static public function method1($arg)
{
return new ABC($arg, true);
}
private function __construct($arg, $isFlag = false)
{
//Do stuff
}
}
Thanks for the help!
Whether it's OK or not depends on what the class is used for.
Anyway, the kind of architecture you're describing is sometimes used for different purposes. The Singleton pattern is a good application of such pratice.
This singleton pattern makes you having more control on the way your class needs to be expressed throughout your program.
let say you want to instanciate only 5 Objects of the same class, you can easily implements that with a counter in the static method.
That is sometimes called 'Factory pattern' as you will notice the way you manage the creation of instances (products).
If you had a family of objects that shared most of their state this may be a sane approach. I can't imagine a situation though that wouldn't be better just to abstract the shared state into it's own object and inject it into each of the new instances. IMHO public statics are almost as evil as globals.
This seems to be the so called factory pattern.
if you declare the constructor private you can not instanciate the class directly.
You have to use the public static methods to use such a class.
Patterns are really great! you should read something about them.
What is better to use in this context, static methods, or simple public method and call them always like this: $request = new Request();
if($request->isPostRequest()){ do smth }
ofcourse its easier to use static, but what is more properly to use?
Class Request {
public static function isSecureConnection() {}
public static function isPostRequest() {}
public static function isAjaxRequest() {}
...etc
}
If each Request is a genuine entity, then it would be better to use non-static members. But if it's not and methods are used in general, like Sinus function in math, then they'd be better to be static.
Overall it'd be better to declare static functions in a class that is just consisted of functions and no data members.
You should always create a class like if it was to be used on a non-static environment.
Then you can use that as a Singleton with lazy-instantiation. Or even as a Static class instantiation. Or even as a Standalone instance object. You decide later what to do with it.
If you start by declaring all members as static you are basically just covering a bunch of Global variables inside a glorified namespace known as a Class. You also will statically allocate the memory used by that class even if you don't call it or use it in your code.
So, just write as a Class, then you decide what to do with it. Static/Non-Static. Singleton/Instance. Factory Pattern or not. Memory Allocator X/DLL bound or whatnot.
The only exception is static members used for book-keeping in behalf of the Object Instances; things like reference counting, caches and things like that. That is the good thing about static/non-static, you can mix and match for some clever behaviors.
What if later you wanted another Request? Or what would happen if you can create more than one because you are in a multithreaded environment? Things will get really strange once you go that route with statics.
It looks like you are handling one particular request.
Now this insinuates you should make it a singleton, and/or use static functions.
Reason:
There is only one request, all the state is defined by the environment delivered to the process. The class methods are just helper functions, and you want to be able to use them without class instance.
On the other hand, you would rarely use static functions with classes that represent one of many, for example one user of many, one question of many.
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
Example:
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
See the reference of Static Keyword from php.net.
If you can, use static methods as a default. static methods run quicker than their non-static counterparts.
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.