r/PHPhelp • • Oct 16 '21

Solved when you would u use a static function?

im coming from python and very new to php

consider this:

    class normalUser
    {
        const rank = NORMAL;
        private $rank = NORMAL;

        static function static_function()
        {
            return self::rank;
        }

        function just_function()
        {
            return $this->rank;
        }
    }

this is my understanding:

	$new_user = new normalUser;
	echo $new_user->just_function();		#call class method in object context
	echo normalUser::static_function();		#without initializing an object of class

this is weird. i guess static methods can be used to grab a class's constant property without instantiating the class or something? i guess a slight performance optimization?

static methods can only access its class's constant properties so if thats not what the implemented static method does that means the method has nothing to do with the class really, in which case i would be better off writing a function that does the same thing outside the class scope?

what r sum practical examples where this kind of weird technique is used?

9 Upvotes

11 comments sorted by

11

u/HolyGonzo Oct 16 '21

So first off, "static methods can only access its class's constant properties" is CLOSE but not quite accurate. Static methods can access constants and also other static properties or methods.

class StaticCling
{
  public static $whom = "Mom";

  public static function SayHi()
  {
    echo "Hi, " . self::$whom . "!"; // OUTPUT: Hi, Mom!
    self::SayBye();                  
  }

  private static function SayBye()
  {
    echo "Bye, " . self::$whom . "!"; // OUTPUT: Bye, Mom!
  }
}

Static methods and properties aren't really about performance. There are just situations where you don't really need or want an instance of something just to call a method inside it.

The two most common use cases I see for this are singletons and factories.

Singletons are where you really only want ONE instance of something. For example, if you have a big application with lots of classes that each need to query the database, it would be a real pain to pass around a database reference into each and every class. And you probably wouldn't want 100 different instances of some "Database" class out there. So instead, you have a static method that you call that manages a single instance of the class and keeps returning it to everyone that calls it.

class Database
{
  private static $instance;
  
  public static function GetConnection()
  {
    if(self::$instance == null)
    {
      self::$instance = new SomeDatabaseDriverClassHere();
    }
    return self::$instance;
  }
}

class DataModelX
{
  public function Save()
  {
    $db = Database::GetConnection();
    $db->query("UPDATE dataModelX ...");
  }
}

class DataModelY
{
  public function Create()
  {
    $db = Database::GetConnection();
    $db->query("INSERT INTO dataModelY ...");
  }
}

So you can see that as "DataModelX" and "DataModelY" classes need the database, they can just call that static function to retrieve and re-use the same database connection.

Factories are just classes that create instances of other classes. At first, that might sound useless, so let's imagine a scenario where you want to create an instance of a class by loading some data from a file. You might do this:

class Car
{
  public $year;
  public $make;
  public $model;

  public function LoadFromFile($file)
  {
    $results = json_decode(file_get_contents($file),true);
    $this->year = $results["YEAR"];
    $this->make = $results["MAKE"];
    $this->model = $results["MODEL"];
  }
}

And you'd use it like this:

$car = new Car();
$car->LoadFromFile("my_car.json");

...BUT what if my_car.json doesn't exist or fails to load? You still have this Car instance, but it doesn't have any data in it! It's pretty much a waste.

However, a factory could give you a static method that produces a Car only if the file load is successful, and otherwise return a null or throw an exception:

class Car
{
  public $year;
  public $make;
  public $model;
}

class CarFactory
{
  public static LoadFromFile($file)
  {
    if(!file_exists($file))
    {
      throw new \Exception("{$file} not found!");
    }

    $results = json_decode(file_get_contents($file),true);

    if(!is_array($results))
    {
      throw new \Exception("{$file} did not decode properly");
    }

    $car = new Car();
    $car->year = $results["YEAR"];
    $car->make = $results["MAKE"];
    $car->model = $results["MODEL"];
    return $car;
  }
}

Now, your car factory takes on all the responsibilities about loading up the data, doing some basic checks, and creating the Car and returning it. So if you call CarFactory::LoadFromFile("my_car.json"), you'll either get a valid Car instance OR you'll get an exception thrown. Meanwhile, your Car model / class doesn't have all that ugly loading code in it, and it can focus solely on managing the data specific to each of its instances.

These are not the only uses for static, but they're two good examples.

4

u/equilni Oct 16 '21

The database example could be done using dependency injection as well.

2

u/HolyGonzo Oct 16 '21

Absolutely but I was trying to keep the singleton example as concise as possible. Still, a good point, so take my upvote!

1

u/djst3rios Oct 16 '21

Another case would be if you had a class, say called Car and you wanted to keep track of how many Car instances you have in total. This is something static, not a unique property for individual "Car" object, so you would make it static.

2

u/[deleted] Oct 17 '21

i got further in this book after posting this and the book also showed a same type of use case, so basically like class variables in python

1

u/Blackhaze84 Oct 16 '21

My clues are: There is no inheritance and the properties are not going to change their value once are required. The best example (and it is how laravel works) are model layer classes. Those that execute crud operations.

1

u/bkdotcom Oct 16 '21
  • factory methods

  • any method where you're not working on a specific instance of something..

  • A static method is nothing more than a namespaced function, Foo::bar() does not significantly differ from foo_bar()

-1

u/Kit_Saels Oct 16 '21

I don't use static functions, I haven't found a job for them.

-1

u/[deleted] Oct 16 '21 edited Oct 16 '21

Its not a good practice.

when you would u use a static function?

Static properties and methods can be used without creating any objects.

You can use it to create classes with small functionality to server/ to be used by main class.

1

u/[deleted] Oct 16 '21

ya i thought so. im at the OOP part of this book im reading and honestly kinda seems like a bit of a mess lol

1

u/HolyGonzo Oct 16 '21

"It's not a good practice" That's not exactly true. There is a time and place for every tool. It's not a good practice to OVERUSE static things but they definitely have their good uses.