开发者

Some instruction needed for PHP OOPS concepts

I need to clear some OOPS concepts in PHP.

  1. Which is faster $this->method(); or self:method();
  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?
  3. what is 开发者_如何学编程factory? How can i use it?
  4. What is singleton? How can i use that?
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜