tags:

views:

104

answers:

4

Hello, people! 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

}
+4  A: 

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.

Hamid Nazari
A: 

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.

chanchal1987
A: 

If you can, use static methods as a default. static methods run quicker than their non-static counterparts.

Cory Collier
A: 

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.

Rui