Silver-0-surfer
Well-Known Member
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'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