Call class method from variable – PHP
Sometimes you have to call the class method from the PHP variable. Let’s say you have a class with few functions with arguments.
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
Then you can create the class object from a variable like the following:
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
$class_name = "User";
$class_obj = new $class_name();
Now to call the method from that object, you can do:
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
$class_name = "User";
$class_obj = new $class_name();
$action_name = "list";
$class_obj->{$action_name}(); // echo "Users list"
You can also pass parameters to the method as well.
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
$class_name = "User";
$class_obj = new $class_name();
$action_name = "fetch";
$class_obj->{$action_name}(3); // echo "User fetch 3"
You can call multiple parameters as well.
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
$class_name = "User";
$class_obj = new $class_name();
$action_name = "update";
$class_obj->{$action_name}(5, "Adnan"); // echo "User update 5, Adnan"
Full code:
<?php
class User
{
public function list()
{
echo "Users list";
}
public function fetch($id)
{
echo "User fetch: " . $id;
}
public function update($id, $name)
{
echo "User update: " . $id . ", " . $name;
}
}
$class_name = "User";
$class_obj = new $class_name();
$action_name = "list";
$class_obj->{$action_name}(); // echo "Users list"
echo "<br />";
$action_name = "fetch";
$class_obj->{$action_name}(3); // echo "User fetch 3"
echo "<br />";
$action_name = "update";
$class_obj->{$action_name}(5, "Adnan"); // echo "User update 5, Adnan"
I have used this technique to create a lightweight PHP framework. Check out our other tutorials on PHP.