Recipe 7.17. Defining Static Properties and Methods7.17.1. ProblemYou want 7.17.2. SolutionDeclare the method as class Format { 7.17.3. DiscussionOccasionally, you want to define a collection of methods in an object, but you want to be able to invoke those methods without instantiating a object. In PHP 5, declaring a method static lets you call it directly: class Format { Since static methods don't require an object instance, use the class name instead of the object. Don't place a dollar sign ($) before the class name. Static methods aren't referenced with an arrow (->), Number formatting doesn't depend on any other object properties or methods. Therefore, it makes sense to declare this method static. This way, for example, inside your shopping cart application, you can format the price of items in a pretty manner with just one line of code and still use an object instead of a global function. Static methods do not operate on a specific instance of the class where they're defined. PHP does not "construct" a temporary object for you to use while you're inside the method. Therefore, you cannot refer to $this inside a static method, because there's no $this on which to operate. Calling a static method is just like calling a regular function. PHP 5 also has a feature known as static properties. Every instance of a class shares these properties in common. Thus, static properties act as class-namespaced global variables. One reason for using a static property is to share a database connection among multiple Database objects. For efficiency, you shouldn't create a new connection to your database every time you instantiate Database. Instead, negotiate a connection the first time and reuse that connection in each additional instance, as shown in Example 7-37. Sharing a static method across instances
Static properties, like static methods, use the double colon notation. To refer to a static property inside of a class, use the special prefix of self. self is to static properties and methods as $this is to instantiated properties and methods. The constructor uses self::$dbh to access the static connection property. When $db is instantiated, dbh is still set to NULL, so the constructor calls This does not occur when you create $db2, since dbh has been set to the database handle. 7.17.4. See AlsoDocumentation on the static keyword at |
Monday, January 11, 2010
Recipe 7.17. Defining Static Properties and Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment