PHP: class variable visibility - php

I'm just a once-in-a-while PHP developer. Now, working on a legacy application, I just hit upon the following problem, which seems very stupid. But I can't get $someString class variable to hold the right value:
class MyClass{
var $someString;
function doSomething(){
//$this->setString(); //this is effectively not called here, but later in getIframe()
$this->buildIframe();
echo $this->someString; //actually, I need someString here, but it is empty
}
function setString(){
$this->someString = "something";
}
function buildIframe(){
$content .= <iframe....>;
}
function getIframe(){
$this->setString();
}
}
$myClassInstance = new MyClass();
$myClassInstance->doSomething();
$myClassInstance->getIframe();
As far as I can see, doSomething() is called in a class context, as I did show.
What am I doing wrong?
EDIT:
I reviewed the code and I think I found whats causing this. There is an iframe embedded into the html output, which is generated at one part and called later on. So the setString() method is actually not called imediately, what I thought first but when invoking the iframe code. So thats why it's not available where I need the string output.
I guess like the code is now, there is no way to get the $someString output except inside the getIframe() method.

This code is 100% correct and working. I've checked it on PHP 5. It echos "something" in string. And it is proper behavior.
From manual:
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Related

How to pass a variable into multiple functions

In my screenshot below you can see I have a list of functions that run a routine, fairly in-depth routine.
Previously, I have ben repeating this routine in multiple classes, but now I would like to consolidate those multiple classes into one class and execute only one function, by passing a variable into that function to determine the output to return.
I know how to pass the variable into "one" function, but how can I pass the variable ($this_id) into my multiple functions below? Basically, whatever $this_id is from get_output($this_id); I want that same variable value to be carried over into the other $this_id functions. See screenshot...
I searched online and all answers I've seen show how to do this in a non static way, but I'm only familiar with calling things statically, really. I tried the obj way, but couldn't get it to work.
Example, execution...
$header = 'CustomTheme_output';
$header::get_output('header');
(please disregard any lose code, the code is what I have so far from trying multiple ways. private $id and __construct are from the online solutions I have been trying)
Could you please clue me in on how I can correctly achieve this? I would be sooo happy to get rid of all the repetitive code, folders and files I have! - Thanks!
Either you pass it directly into each method call:
public function foo($this_id) {
$this->bar($this_id);
}
Or you make it a class attribute, and simply ACCESS it from the various methods:
public function foo($this_id) {
$this->id = $this_id;
$this->bar();
}
public function bar() {
do_something($this->id);
}

making a class's static-member a function (closure) does not work

(PHP7)
Consider the following code, which tries to assign a function to a variable, and then make sure it is called only once.
class a{
static public $b;
static public function init(){
self::$b();
self::$b=function(){};
}
}
a::$b=function(){echo 'Here I do very heavy stuff, but will happen only in the first time I call init()';};
for($i=0;$i<1000;$i++){
a::init();
}
In php7 it will give an error that it expects a::$b to be a string (the function name to call).
If I use pure variables and not static members, it will work.
My question, is this suppose to work, or not, or is there a small tweak I can do for this to work without pure vars?
You can either use PHP 7 Uniform Variable Syntax:
(self::$b)();
Or a temporary variable in PHP 5+ (including 7):
$init = self::$b;
$init();
As seen on 3v4l.org.

call_user_func() or $callback() not working

In a PHP routing file, I want to make a callback to a function called homepage_display().
The function name is in the $callback variable, and when I make the call, it doesn't work:
$callback = "homepage_display";
$callback(); // doesn't work
call_user_func($callback); // doesn't work either
homepage_display(); // works!!
Whereas this specific piece of code just above works in any snippet, the same mechanism doesn't work in one of my functions. Any idea of what can cause such a behavior? I tried removing the _ thinking it might be an encoding problem, but it doesn't solve anything.
EDIT:
To make my point absolutely clear, I added an explicit assignation $callback="homepage_display";, just before calling it as a callback function. You can see on this picture that it just does not work. Whereas calling homepage_display(); directly, does. If somebody understands something, I'm curious :)
Not working:
Working:
The answer, in one word: namespace foo\bar;.
One cannot call $callback(); when in the scope of a non-global namespace.
One has to call call_user_func(__NAMESPACE__.'\\'.$callback); instead.
It can get tricky sometimes ;)
Works fine here:
php > function foo() { echo 'foo!'; }
php > $bar = 'foo';
php > call_user_func($bar);
foo!
php > $bar();
foo!
Did you verify that your testRoute() actually returns true? If it doesn't, then your "autoloader" will never get called.

Call a non-global variable from a function?

During the development of a Joomla! plugin, I ran across something really interesting. One of the events does not have a return value, but it calls variables from inside the function. Prior knowledge tells me this should only work if the variables are global inside the function, yet the dispatcher is able to call the variables from outside the function.
EDIT: I just discovered that the variable that is accessed from inside the function needs to be one of the paramaters! Could this be func_get_params() or call_user_func()?
Calling Code:
$instance = JDispatcher::getInstance();
$instance->trigger(onJoomCalledEvent, array(&$link, $other_params));
Plugin (snippet):
class plgMyPlugin extends JPlugin{
onJoomCalledEvent($link, $other_params){
$link = "Some Value Here";
return false;
}
}
This function returns false, yet somehow the application (Joomla!) is able to extract the value of $link. How is this done?
Does the plug-in definition look like this:
class plgMyPlugin extends JPlugin{
onJoomCalledEvent(&$link, $other_params){
$link = "Some Value Here";
return false;
}
}
Than it's pass by reference. If it's indeed the way you posted above than it's call time pass by reference which is deprecated and emits a warning starting with PHP 5.3.

PHP create_function Instance variable - Unable to call anonymous function: Follow up

This is somewhat a follow up to a previous question - but I've distilled the question down and have the "works" vs. "doesn't work" cases narrowed down much more precisely.
My Goal:
I have a class MyClass that has an instance variable myFunction. Upon creating a MyClass object (instantiating), the constructor assigns the instance variable myFunction with the result of a call to create_function (where the code and args come from a db call).
Once this object of type MyClass is created (and stored as an instance variable of another class elsewhere) I want to be able to call myFunction (the instance variable anonymous function) from "anywhere" that I have the MyClass object.
Experimental Cases -- below is my highly simplified test code to illustrate what works vs. what doesn't (i.e. when the expected functionality breaks)
class MyClass extends AnotherClass {
public $myFunction;
function __construct() {
$functionCode = 'echo "NyanNyanNyan";';
$this->myFunction();
/*Now the following code works as expected if put in here for testing*/
$anonFunc = $this->myFunction;
$anonFunc(); //This call works just fine (echos to page)!
/*And if i make this call, it works too! */
self::TestCallAnon();
}
public function TestCallAnon() {
$anonFunc2 = $this->myFunction;
$anonFunc2();
}
}
However, if I do the following (in another file, it errors saying undefined function () in... within the Apache error log.
//I'm using Yii framework, and this is getting the user
//objects instance variable 'myClass'.
$object = Yii::app()->user->myClass;
$object->TestCallAnon(); // **FAILS**
or
$func = $object->myFunction;
$func(); // ** ALSO FAILS **
In addition, several variations of calls to call_user_func and call_user_func_array don't work.
If anyone is able to offer any insight or help that would be great :).
Thanks in advance!
You can't pass references to functions around in PHP like you can in for instance JavaScript.
call_user_func has limited functionality. You can use it like so:
class MyClass {
function func() {}
static function func() {}
}
function myfunc() {}
$i = new MyClass();
call_user_func("myfunc", $args);
call_user_func(array($i, "func"), $args);
call_user_func(array(MyClass, "staticFunc"), $args);
I ended up solving this issue via a workaround that ended up being a better choice anyways.
In the end I ended up having a static class that had a method to randomly return one of the possible identifiers, and then another method which accepted that identifier to build the anonymous function upon each class.
Slightly less elegant than I would like but it ends up working well.
Thanks to everyone for your efforts.

Categories