-1

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.

ulrich
  • 1,431
  • 3
  • 17
  • 46
  • Is this your orginal code? This should work just fine. – Daan Jul 29 '15 at 08:40
  • when you echo the $someString, it is no empty anymore because of assigning. – Marcos Segovia Jul 29 '15 at 08:40
  • it works fine, what's the problem? – Javi Jul 29 '15 at 08:41
  • I just executed your exact code and i get "something" echo'd. Could you provide us with a PHP version? – Werring Jul 29 '15 at 08:42
  • 1
    well, as I said, this is from a legacy application, so it's not the original code but it is what I did boil the problematic code down to. If that's is correct, what I thought too, maybe I have to check the legacy code for other relevant stuff that prevents this from working correctly. – ulrich Jul 29 '15 at 08:44
  • [**Can't reproduce your problem**](http://3v4l.org/WTLA0) Please show us an example to reproduce your problem! – Rizier123 Jul 29 '15 at 08:47
  • Thanks for the comments. I edited my question on the part which I think is causing the empty $someString variable in my legacy code. – ulrich Jul 29 '15 at 09:27

1 Answers1

5

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.

Robert
  • 19,800
  • 5
  • 55
  • 85