Undefined property in dynamic variable of a PHP class - php

I am trying to get a dynamic variable value in a PHP class but not sure how to do this. Here's my code:
<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->date_{$type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>
I am getting following error:
Notice: Undefined property: Test::$date_ in...
Notice: Undefined variable: type in ...
If I write echo $this->date_added; in place of echo $this->date_{$type}; then I get output "Pass".
How to fix it and do it properly?

Since you're using variable variables, put them in quotes, then concatenate:
echo $this->{'date_' . $this->type};
// not $type, use `$this->` since it's part of your properties
Or using via formatted string (double quotes will work as well):
echo $this->{"date_{$this->type}"};

<?php
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
echo $this->{'date_' . $this->type};
}
}
$test = new Test();
$test->set_status();
$test->get_status();
?>

You can do it multiple ways, date_{$type} is not valid expression and to acccess the class property you have to use this keyword .
class Test
{
public $type = "added";
public $date_added;
public function set_status()
{
$this->date_added = "Pass";
}
public function get_status()
{
$prop = 'date_'.$this->type;
echo $this->{'date_'.$this->type}; # one way to do it
echo $this->$prop; # another way to do it
echo $this->{"date_{$this->type}"}; # another way to do it
}
}
$test = new Test();
$test->set_status();
$test->get_status();

Related

PHP - ReflectionFunction - Function Test::test_function() does not exist

I could use RefexionFunction outside of a class, but inside a class I get an exception.
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
<?php
function parameters($functionName,$args){
$f = new ReflectionFunction($functionName);
....
}
class Test{
public function test_functionA($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
protected function test_functionB($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
private function test_functionC($abc,$d,$e,$f) {
parameters(__METHOD__,func_get_args());
}
}
$test = new Test();
$test->test_function('something',1,2,array(123,456));
?>
Appreciate your help.
Your error:
Fatal error: Uncaught ReflectionException: Function Test::test_function() does not exist in test.php.
Doesn't refer to the function name quite as you expect it to.
ReflectionClass docs says this:
The ReflectionClass class reports information about a class.
ref: https://secure.php.net/manual/en/class.reflectionclass.php
You want to use a combination of methods available in that class to get information about the passed method like this:
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
}
You first pass the class before checking if the function exists. You can then use the built-in function hasMethod to check if the function exists. You then use the parameters function like this:
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
All together the code looks like this:
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
class paramsHelper
{
public function parameters($class, $fnc)
{
$f = new ReflectionClass($class);
$f->getMethod($fnc);
if ($f->hasMethod($fnc)) {
return 'howdy folks';
} else {
return 'not so howdy folks';
}
return $f;
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction()
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';
One of your other problems is that __METHOD__ actually returns a string like this: Test::testFunction not testFunction - hence my use of __FUNCTION__ instead.
Edit:
To get the parameters of the passed method, change your parameters method to this:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
This uses ReflectionMethod in place of ReflectionClass - this is more inline with your intended use.
ref: https://secure.php.net/manual/en/class.reflectionmethod.php
use:
class paramsHelper
{
public function getMethodParameters($class, $fnc)
{
$f = new ReflectionMethod($class, $fnc);
echo '<pre>';
print_r($f->getParameters());
echo '</pre>';
}
}
class Test
{
protected $helper;
public function __construct($helper)
{
$this->helper = $helper;
}
public function testFunction($a = '', $b = 1, $c = 3)
{
return $this->helper->parameters(__CLASS__, __FUNCTION__);
}
}
$test = new Test(new paramsHelper());
echo '<pre>';
print_r($test->testFunction());
echo '</pre>';

How To Get Variable From Constructor So It Can Be Used In Other Functions?

I have this code :
<?php
class Email{
public $mandrill_host;
public function __construct() {
$this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
$this->mandrill_host = $config_ini['mandrill']['host'];
}
public function sendEmail () {
$res = $this->mandrill_host;
return $res;
}
}
$test = new Email;
echo $test->sendEmail ();
?>
and it gives me an empty result. it seems that the constructor method doesn't give the variable needed in sendEmail function. even though I already declared as public variable in class level.
how to get $this->mandrill_host from constructor so I can use it in any other method? what did I miss here?
Try
class Email{
public $mandrill_host;
public $config_ini; //you are missing this
public function __construct() {
$this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
$this->mandrill_host = $this->config_ini['mandrill']['host'];
}
public function sendEmail () {
$res = $this->mandrill_host;
return $res;
}
}
$test = new Email;
echo $test->sendEmail ();
?>

How return a value from one class function to another class function in PHP

I am trying to get the value of a varibale if a condition is tru from one class function to another class function.
Could you please let me know how do i do this(I am new to PHP.)
Code:
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
}
}
Class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$test = $var1;
echo "$test";
}
Here you can see I need $var1 variable value from ErrorList class to Error class.
Thanks in advance.
Regards,
Tejesh.B
<?php
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
return $var1;
}
}
}
class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$call_class = new ErrorList();
$get_val = $call_class->getErrorsSince();
$test = $get_val;
echo $test;
}
}
?>

Trouble with using globally defined variables: 'Use of undefined constant'

I have this code:
<?php
$db_initiallized = false;
$db_connection = NULL;
function db_init()
{
global $db_initiallized, $db_connection;
if(!$db_initiallized) //error occurs on this line
{
$db_connection = mysql_connect("server", "username", "password");
if(!$db_connection)
{
echo 'Connection failure!';
exit();
}
$db_initiallized = true;
}
}
?>
And I get the error:
Use of undefined constant
I'm not sure why this error is occurring. Perhaps I am declaring global variables wrong. What's going on here?
The $GLOBALS array can be used instead:
$GLOBALS['db_initiallized'] = false;
$GLOBALS['db_connection'] = NULL;
function db_init(){
echo $GLOBALS['db_initiallized'];
echo $GLOBALS['db_connection'];
}
OR
If the variable is not going to change you could use define.
define('db_initiallized', FALSE);
define('db_connection', NULL);
function db_init()
{
echo db_initiallized;
echo db_connection;
}
OR
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);

Pass variables from class instance to its extended method

I'm trying to pass a variable to a method in an extended class, but it's not working.
Here's the sample code:
class set2 extends set1
{
function Body($variable) {
}
}
$start2 = new set2();
$start2->Body('some text');
The last line is the part I'm trying to get to work. I'm not sure if I should have a constructor instead to do it or how it's best to get it to work.
I figured it out. I just added a public variable instead and passed its value like this:
class set2 extends set1
{
public $variable = NULL;
function Body() {
echo $this->variable;
}
}
$start2 = new set2();
$start2->variable = 'Some Text';
Three different ways of doing what I think you're trying to do:
class set1
{
protected $headVariable;
function Head() {
echo $this->headVariable;
}
function Body($variable) {
echo $variable;
}
function Foot() {
echo static::$footVariable;
}
}
class set2 extends set1
{
protected static $footVariable;
function Head($variable) {
$this->headVariable = $variable;
parent::Head();
}
function Body($variable) {
parent::Body($variable);
}
function Foot($variable) {
self::$footVariable = $variable;
parent::Foot();
}
}
$start2 = new set2();
$start2->Head('some text');
$start2->Body('some more text');
$start2->Foot('yet more text');

Categories