Jump to content
  • Advertisement
Sign in to follow this  
TheOddMan

[web] PHP: Accessing static functions via strings

This topic is 4364 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know in PHP you can instantiate a class through a variable like this:
$theClass = "ClassName";
$theObject = new $theClass;
This creates a new object of class Classname. My question is this: Is there anyway to access a static function of a class through a similar method? I already tried this and got an error in hebrew(!):
$theClass::StaticFunction();

Share this post


Link to post
Share on other sites
Advertisement
The proper usage of OOP would be:

<?php
$user = new User();

// print object and its member variables
echo '<pre>';
print_r($user);
echo '</pre>';

// example use
$data = array(
'fname' => 'Matthew',
'lname' => 'Miller',
'username' => 'Mathachew'
);

$retval = $user->AddUser($data);

// OR performing the same action without creating the object

$retval = User::AddUser($data);

echo $retval;
?>





In the User Class:

<?php
Class User
{
var $id, $fname, $lname, $username;

function __construct($id = false)
{
if($id !== false)
$this->$id = $id;
}

function AddUser($data)
{
// Validate contents of $data here or
// before calling the function

// Code/SQL to add user goes here

return $retval;
}
}
?>





It's been a while since I've used OOP, and longer since I've used it in a dynamic manner such as that. Perhaps trying {$theClass}::StaticFunction(), but I'm not sure. Hope this helps.

Edit: The above example assumes PHP5. If PHP4, replace __construct with User in the above example.

Share this post


Link to post
Share on other sites
Heh, I wasn't paying that much attention. In your example replace

$theClass::StaticFunction();

with

$theObject->StaticFunction();

and see if that works for you.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!