I successfully instantiated the object class but I can’t figure out how to call a function.
Here is my PHP code:
$obj = new router();
class router{
public function __construct(){
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo "GET";
$page = 'index';
$funct = 'myfuncempty';
if (!empty ($_GET)){
$page = $_GET['page'];
$funct = $_GET['func'];
}
$obj = new $page(); //instantiating object with get from class
$obj->funct;
}
else{
echo "POST";
}
}
}
class index{
public function __construct(){
echo "hello I'm index";
}
public function myfunc(){
echo "yo";
}
public function myfuncempty(){
echo "empty get";
}
}
class login{
public function __construct(){
echo "hello I'm login";
}
public function loggedin(){
echo "you're logged in";
}
public function loggedinempty(){
echo "its empty";
}
}
And this is the HTML form that I use to pass variables via GET:
<html>
<head></head>
<body>
<form action="index.php" method="POST"><input type ="text" name="page" id="page" /><input type="submit" /></form>
<form action="index.php" method="GET">Page:<input type="text" name="page" id="page" />Function:<input type="text" name="func" id="func" /><input type= "submit" />
</body>
</html>
When I type index in for page and myfunc in for function, I get this response:
GEThello I'm login Notice: Undefined property: login::$funct in /home/cr47/public_html/final_project/index.php on line 27
So, it is passing the ‘page’ correctly and instantiating the object but it is not correctly calling the myfunc function.
Any ideas?
Replace
$obj->funct;with$obj->$funct();But be careful. You shouldn’t let your users instantiate arbitrary classes. At least use a whitelist or require them to be a subclass of some custom class only used by your classes which are safe (i.e. no public methods that do anything a user shouldn’t be able to do).