How to make function from string variables? - php

How to make function from string? I am new to php programming and wanted solution for below code.
If I want to access page for test2.php?page=test for below class:
class test{
public static function getTest(){
//code here....
};
}
and wanted to access test2.php?page=test using variable so what should I do?
require_once "test.php";
$variabe = $_GET['page'];
test::get . ucfirst($variable) . ();

You can do it like this:
<?php
class test{
public static function getTest(){
echo 'getTest()!!';
}
}
$variable = 'Test';
// since we are interpolating a raw string, input from $_GET, and a function we need to let PHP know to fully complete this string before using it as a function call
test::{"get".ucfirst($variable)}();
// Build the full method name ahead of time and you can just call it using the variable
$variable2 = 'getTest';
test::$variable2();
Output:
getTest()!!

Related

Cannot Access Global Variable inside function INSIDE public function PHP

Good day. I'm trying to execute a function. i declare a global variable to get data (variable) outside the function, and the function i put inside a public function of a Class.
class Test {
public function execute(){
$data = "Apple";
function sayHello() {
global $data;
echo "DATA => ". $data;
}
sayHello();
}
}
$test = new Test;
$test->execute();
The expected result:
DATA => Apple
The real result:
DATA =>
the global variable is not getting the variable outside the function. Why it happened? Thank you for the help.
$data is not a global variable. It's inside another function, inside a class. A global variable sits outside any function or class.
But anyway your use case is unusual - there's rarely a need to nest functions like you've done. A more conventional, logical and usable implementation of these functions would potentially look like this:
class Test {
public function execute(){
$data = "Apple";
$this->sayHello($data);
}
private function sayHello($data) {
echo "DATA => ". $data;
}
}
$test = new Test;
$test->execute();
Working demo: http://sandbox.onlinephpfunctions.com/code/e91b98bb15fcfa71b1c6cbbc305b5a93df678e8b
(This is just one option, but it's a reasonable one, although since this is clearly a reduced, abstract example, it's hard to be sure what your real scenario would actually require or be best served by.)

Calling Static Member Function on Class Stored as String in PHP?

Since I am aware that one can call a member function on Class stored as String. But I was wondering if there is any way to do the same for static member function in PHP.
for example:
class A
{
public static function run(){
echo "OK";
}
}
"A"::"run"()
Something similar to the above example.
Please help me out. Thanks in advance.
you can call class as string like this
<?php
class A
{
public static function run()
{
echo "OK";
}
}
$stringClass = "A";
$staticMethod = "run";
$stringClass::$staticMethod();
To tackle this type of problem, which I faced while developing a user-friendly PHP framework, is to store the class name and static method name as a string in some PHP variables.
$className = "A";
$methodName = "run";
And call it like so:
$className::$methodName();
or second way
$func = "A::run";
$func(); //or
"A::run"();
And this is how one calls the static method on the class stored as a string.
This one of the ways, more can be found at https://www.designcise.com/web/tutorial/how-to-dynamically-invoke-a-class-method-in-php

Can i use a class variable as variable function inside the same class's method in one single line?

I can use the instance variable as dynamic variable function inside the same class's method. But only declaring it locally to another variable inside the method. I can't use it like: "$this->$this->functionName". What i mean is:
This works:
TheClass.php
<?PHP
class TheClass{
public $functionName;
function setFunctionName($name){
$this->functionName = $name;
}
function processClass(){
$tempFunctionName = $this->functionName;
$this->$tempFunctionName();
}
function testFunction(){
echo "this works";
}
}
?>
main.php
<?PHP
include "TheClass.php";
$theClass = new TheClass();
$theClass->setFunctionName('testFunction');
$theClass->processClass();
?>
But i can't use it all in one line like this way:
function processClass(){
$this->$this->functionName();
}
Is there a way (out of using call_user_func ) to use it this way or have i to use it with locally setting it.
Wrap it in {}
function processClass(){
$this->{$this->functionName}();
}
Chaining method:
function setFunctionName($name){
$this->functionName = $name;
return $this;
}
$theClass->setFunctionName('testFunction')->processClass();

php how to: save session variable into a static class variable

Below code works fine:
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities
{
public static $color;
function display()
{
echo utilities::$color = $_SESSION['color'];
}
}
utilities::display(); ?>
This is what I want but doesn't work:
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo utilities::$color;
} } utilities::display(); ?>
I get this error: Parse error: syntax error, unexpected T_VARIABLE in C:\Inetpub\vhosts\morsemfgco.com\httpdocs\secure2\scrap\class.php on line 7
Php doesn't like session variables being stored outside of functions. Why? Is it a syntax problem or what? I don't want to have to instantiate objects because for just calling utility functions and I need a few session variables to be stored globally. I do not want to call a init() function to store the global session variables every time I run a function either. Solutions?
In a class you can use SESSION only in methods...
Actually, if you want to do something in a class, you must code it in a method...
A class is not a function. It has some variables -as attributes- and some functions -as method- You can define variables, you can initialize them. But you can't do any operation on them outside of a method...
for example
public static $var1; // OK!
public static $var2=5; //OK!
public static $var3=5+5; //ERROR
If you want to set them like this you must use constructor... (but remember: constructors aren't called until the object is created...)
<?php
session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color;
function __construct()
{
$this->color=$_SESSION['color'];
}
function display()
{
echo utilities::$color;
}
}
utilities::display(); //empty output, because constructor wasn't invoked...
$obj=new utilities();
echo "<br>".$obj->color;
?>
From the PHP manual:-
Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not allowed.
So while you may initialize a static
property to an integer or array (for
instance), you may not initialize it
to another variable, to a function
return value, or to an object.
You say that you need your session variables to be stored globally? They are $_SESSION is what is known as a "super global"
<?php
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo $_SESSION['color'];
}
}
utilities::display(); ?>

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

Categories