Why is PHP Saying that my object is empty ?
Here is a simple use case.
It keeps returning the following error :
Fatal error: Cannot access empty property in C:\AdvancedApp\myApp.php on line 10.
class myClass
{
public $myFunction = "Hello World";
}
$class = new myClass();
echo $class->$myFunction;
The correct use of property is:
echo $class->myFunction;
What you did is used variable variables, the following will work:
$name = "myFunction" ;
echo $class->$name ;
Drop the $ sign from $myClass->$myFunction so it will be $myClass->myFunction, and what's with the variable name. Use something else, like myValue...
Related
I have this piece of code:
private function _resolveCustomEntries($fields)
{
foreach ($fields as &$value) {
if (array_key_exists('custom', $value)) {
if (method_exists($this, $value['custom'])) {
$value['custom'] = $this->$value['custom'](); //variableInterpolation
}
}
}
return $fields;
}
I ran a PHP 7.2 compatibility check and it complained here with the "variableInterpolation" on the marked line. When I run this code, the PHP log tells me this:
ERR (3): Notice: Array to string conversion in
/public_html/lib/KiTT/Payment/Widget.php on line 217
Thats the same line where the "variableInterpolation" check failed. So how would I rewrite this code so it works in PHP 7.2?
Thanks!
Solution:
$value['custom'] = $this->$value['custom']();
has to look like this:
$value['custom'] = $this->{$value['custom']}();
It's a matter of order variables are evaled.
With
class x {
public function y() {
echo 'ok';
}
}
$x = new x();
$y = array('i' => 'y');
Then
$x->$y['i']();
Fails because PHP first tries to cast the $y variable into a string, and get the matching property of $x (which btw does not exist), then tries to get the index 'i' or that unexisting property, and then tries to run it as a callable.
Hence 3 errors:
Array to string conversion
Undefined property x::$Array
Function name must be a string (nda: the undefined property returns NULL)
Instead, curly brace the variable to set the resolving order:
$x->$y['i']();
Will work. So use $this->{$value['custom']}()
This will throw an array to string conversion in 7.2
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$value['custom'] = $this->$value['custom']();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
But it will execute just fine in 5.6.
Then i changed the snippet to this, not calling the method directly casting the array key to function name, but initializing a string (hopefully, there is no type validation in your code) variable with the function name first:
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$functionName = $value['custom'];
$value['custom'] = $this->$functionName();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
This will run just fine in php 7.2
You could try rewriting your code using complex (curly) syntax, you can read more about it here.
Your code would look something like this.
$value['custom'] = $this->{$value['custom']}();
Edit: moved the curly braces to correct positions.
I recently made a class in PHP
I am trying to declare a variable within class and using str_replace in a function but its show undefined variable
class Status{
$words = array(".com",".net",".co.uk",".tk","co.cc");
$replace = " ";
function getRoomName($roomlink)
{
echo str_replace($words,$replace,$roomlink);
}
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");
Any kind of help would be appreciated thanks you
Your variables in the function getRoomname() aren't adressed properly. Your syntax assumes the variables are either declared within the function or passed while calling the function (which they aren't).
To do this within a class, do it while using $this->, like this:
function getRoomName($roomlink)
{
echo str_replace($this->words,$this->replace,$roomlink);
}
For further informations, please have a look into this page of the manual.
Maybe because of the version or something, when I tested your exact code, I got syntax error, unexpected '$words' (T_VARIABLE), expecting function (T_FUNCTION), so setting your variables to private or public should fix this one.
About the undefined varible, you have to use $this-> to access them from your class. Take a look:
class Status{
private $words = array(".com",".net",".co.uk",".tk","co.cc"); // changed
private $replace = " "; // changed
function getRoomName($roomlink){
echo str_replace($this->words, $this->replace, $roomlink); // changed
}
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");
Also, since getRoomName isn't returning anything, echoing it doesn't do much. You could just:$status->getRoomName("http://darsekarbala.com/azadari/");.
or change to :
return str_replace($this->words, $this->replace, $roomlink);
Short Version: Why can't we access a function like this:
$b = "simple_print()";
$obj->$b;
Complete Version:
Suppose we have a class User defined like this:
class User {
public $name;
function simple_print() {
echo "Just Printing" . "<br>";
}
}
Now if a create an User object and set the name of it we can print its name using
$obj = new User;
$obj->name = "John";
echo $obj->name;
Although it is strange we also can do something like this in order to print "John":
$a = "name";
echo $obj->$a;
But we can't access a function using the same idea:
$b = "simple_print()";
$obj->$b;
Why? Shouldn't it work the same way?
Also, does anyone know what is it called? I tried to look for "accessing a member through a variable" and "using a method through a variable with the name of it" but I didn't find anything related to this.
Extra info: The version of PHP I'm using is: PHP version: 5.5.9-1ubuntu4.7
You were very close, but made a small logical mistake. Try this instead:
$b = 'simple_print';
$obj->$b();
This is because the method is accessed by it's name, which is simple_print, not simple_print(). The execution is triggered by the parenthesis, but that is not part of the name, so of how you access the method.
Here is a short example:
<?php
class Test
{
public function simple_print() {
echo "Hello world!\n";
}
}
$object = new Test;
$method = 'simple_print';
$object->$method();
As expected it creates the output Hello world! if executed on CLI.
Trying to crate objects dynamically for a plug in system (work in progress)
heres my code using $this->module->load_module('test'); to use the method that creates the dynamic objects. Following code is the function that loads the class's and makes use of an auto loader, i have checked that its getting the correct file etc.
<?php
class BaseModule {
function __construct() {
}
function load_module($module){
echo 'Module = '.$module.'<br />';
$object_name = $module . "Controller";
$this->$$module = new $object_name();
}
}
Here is a test module that it would load when invoking $this->module->load_module('test'); and it creates the object outputting the test strings via echo statements. Heres the code for the test module that was constructed. Which should cause no problems as there is not really a solution but just an output string, but posted any way.
<?php
class testController {
function __construct() {
echo 'test controller from modules <br />';
}
}
However when running the page i am getting some errors can any one help out?
Notice: Undefined variable: test in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
Fatal error: Cannot access empty property in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
I have a simple question (i guess).
I'm getting the name of the function inside a variable from database. After that, i want to run the specific function. How can i echo the function's name inside the php file?
The code is something like this:
$variable= get_specific_option;
//execute function
$variable_somesuffix();
The "somesuffix" will be a simple text. I tried all the things i had in mind but nothing worked.
You want call_user_func
function hello($name="world")
{
echo "hello $name";
}
$func = "hello";
//execute function
call_user_func($func);
> hello world
call_user_func($func, "byron");
> hello byron
You want variable variables.
Here's some sample code to show you how it works, and the errors produced:
function get_specific_option() {
return 'fakeFunctionName';
}
$variable = get_specific_option();
$variable();
// Fatal error: Call to undefined function fakeFunctionName()
$test = $variable . '_somesuffix';
$test();
// Fatal error: Call to undefined function fakeFunctionName_somesuffix()
There are two ways you can do this. Assuming:
function foo_1() {
echo "foo 1\n";
}
You can use call_user_func():
$var = 'foo';
call_user_func($foo . '_1');
or do this:
$var = 'foo';
$func = $var . '_1';
$func();
Unfortunately you can't do the last one directly (ie ($var . '_1')(); is a syntax error).
You can also do sprintf($string).