Jump to content

static class methods


AP81

Recommended Posts

Static methods are here for processes that don't depend on the object, but still have to be in the class. Example:

 

class TextWriter
{
    private $text;

    public function __construct($text)
    {
        $this->text = (string) $text;
    }

    public function write()
    {
        file_put_contents('bla.txt', self::formatText($this->text));
    }

    private static function formatText($str)
    {
       return trim($str);
    }
}

Link to comment
https://forums.phpfreaks.com/topic/97893-static-class-methods/#findComment-501064
Share on other sites

another example that might help clear it up

<?php
class user extend base_model
{
   public $id;
   public $username;

   public static function get_all()
   {
      //code to return all users
   }
}

$users = user::get_all();
?>

 

Now even tho the user object stores information, it can be used to store static methods there return multiple user object.

Link to comment
https://forums.phpfreaks.com/topic/97893-static-class-methods/#findComment-501160
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.