• Advertisement
Sign in to follow this  

[web] PHP: Accessing static functions via strings

This topic is 4180 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
I'm not sure that you can do what you want without using eval():

eval("$theClass::StaticFunction();");

Share this post


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

  • Advertisement