Public Static Function PHP

Silver-0-surfer

Well-Known Member
Joined
Jan 5, 2008
Messages
317
Reaction score
7
Location
CPT
Hi,

I'm kind of new to OOP and PHP so please be gentle.

I want to setup a few public static functions that can be called without having to instantiate an object. Just to do a few converts basically so I have the following.


class Converter extends PDO{

function __construct() {
parent::__construct();
}

/*
* This function should convert a userid to a username
*/
public static function UserID_UserName($user_id)
{
$db = new Database();

$sth = $db->prepare("SELECT name FROM users WHERE user_id = :user_id");
$sth->execute(array(
':user_id' => $user_id

));
$name = $sth->fetch();
return $name['name'];

}


Now, the code above works fine but I'm sure its not the correct way to do it. What I want to do (in this example) is convert a user id to username, the info is located in a database.

now what I originally tried was this

public static function UserID_UserName($user_id)
{
$sth = $this->prepare("SELECT name FROM users WHERE user_id = :user_id");
$sth->execute(array(
':user_id' => $user_id

));
$name = $sth->fetch();
return $name['name'];

}

but then it moans everytime about using "$this->" inside a static function. I read that I should use "self::" but that didn't work either.

The problem I have (or think I have) is that there are like 20 converters inside this class. Surely its not a good idea to instantiate an object in each of the methods? surely if I construct the parent class I should be able to use $this->?

any advice on how to do this correctly would be amazing
 
I don't know PHP, but the basic premise of static methods is that making a method static implies that it does not have access to anything outside of that specific method's scope. You can't use this-> as there is no "this" in a static method (you haven't instantiated the class, which is essentially what this-> points to, so it can't be available). If you want to use something in a static method it either has to be a static member, another static method or something you instantiate in the method.
 
$this only works on instances of the class. It literally means "this instance"
 
Why in this case would you want to use $this instead of "new Database()" or you could have a static method called prepare(String sql)

Horrible abbreviating too, eg "UserID_UserName", "$sth"

Why not rather usernameByUserId or userIdToUsername?
$sth, I can't even work out what that could mean. There is NEVER ( ok maybe 99%, things like loop indexes are fine, but those are more like constructs and universally understood) a reason to abbreviate, and is plain sloppy IMO (acronyms are fine though)
 
Last edited:
Rather use a singleton

Code:
       /**
	 * Singleton
	 *
	 * @return object
	 */

	public static function get()
	{
		static $instance = null;
		if(isset($instance)==false)
		{
			$instance = new this_class;
		}
		return $instance;
	}


Then you can call your function: this_class::get()->function_name();
 
that singleton isnt threadsafe.

there is a chance that 2 calls will get into the if block. then another static method could be using $instance, and half way though, that $instance gets replaced by a new instance

you could fix it using a double check and a semaphore (wont work in windows though), something like:

Code:
public static function get()
	{
		static $instance = null;
		if(!isset($instance))
		{
                        sem_aquire();
                        try {
                           if(!isset($instance)) {
			      $instance = new this_class;
                           }
                        } finally {
                           sem_release();
                        }
		}
		return $instance;
	}

my php syntax could be off
 
Last edited:
kabal, PHP isn't multi-threaded, so there is no need for semaphores or locks - or at least I've never had to use them in PHP.
I actually had to try and run multiple PHP threads yesterday to speed up my report generation.

You may need to use database locking though, because there may be multiple instances of the same PHP script running.
 
Last edited:
Ouch, so everything is blocking? Or is it 1 thread per instance, with multiple instances? And then static methods/members aren't really even static, as they are re initialized on every instance?

Never used php, so was just adapting singletons from languages like Delphi and java
 
Last edited:
Ouch, so everything is blocking? Or is it 1 thread per instance, with multiple instances? And then static methods/members aren't really even static, as they are re initialized on every instance?

Never used php, so was just adapting singletons from languages like Delphi (critical sections and semaphores) and java (synchronized)

My code example is found in just about every framework in PHP but its very seldom you would run threads in PHP. In 7 years I've only done it once and that was for a CLI script for report generation.

Agree with Pada on the DB locking.
 
Hehe cbrunsdonza. Seems like my PHP threaded use case was exactly the same. Like I had to generate a report with like 2 million records, which took about 15 minutes on a single MySQL thread. I then split it up into 8 threads, and then it took less than 2.5 minutes in total.

@kabal:
PHP would run 1 instance per HTTP thread. So if you open up 7 tabs in your browser to the same script, it would run 7 instances/threads of PHP, with all of them using their own stack/variables.
When I did the multi-threaded PHP reporting, I actually ran into the issue that Firefox could only open 7 connections simultaneously to a single server - unless you go and tweak it in about:config :D
 
Top
Sign up to the MyBroadband newsletter
X