AP81 Posted March 26, 2008 Share Posted March 26, 2008 Hi guys, I am having a little trouble grasping when to use static methods in a class. The obvious benefit is for a singleton class, but what benefit is there of using static functions in a class? Can someone give me a real world example? Thanks. Link to comment https://forums.phpfreaks.com/topic/97893-static-class-methods/ Share on other sites More sharing options...
puritania Posted March 26, 2008 Share Posted March 26, 2008 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 More sharing options...
Liquid Fire Posted March 26, 2008 Share Posted March 26, 2008 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 More sharing options...
AP81 Posted March 27, 2008 Author Share Posted March 27, 2008 Thanks for clearing that up. Link to comment https://forums.phpfreaks.com/topic/97893-static-class-methods/#findComment-501814 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.