Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>All of the above answers are functionally correct. </p> <p>You asked "why" - the reason is due to the programming term 'scope'. Scope defines what variables are visible, and when they are visible. Your example code defines a class-level variable $helloWorld and also a class method which takes a parameter $helloWorld.</p> <p>The only variable that is 'in scope' when the function executes is the one passed as a parameter. So, when the code later invokes that method without assigning a value to the parameter you get an error trying to output its value (since it doesn't have one). At this point the method can't see the class-level variable as it is not in scope.</p> <p>A solution, as above, is to either pass a value to the function's parameter so that it is defined (and hence no error is generated)</p> <pre><code>$saySomething = new saySomething(); $saySomething-&gt;sayHelloWorld('Hello world... again'); </code></pre> <p>Which would pass a value to the class method, and you would see 'Hello world... again' printed to the screen. </p> <p>This may, or may not, be what you intended to do. If you wished to understand how to bring the class level variable into scope, then the most common way is to use the pre-defined PHP variable '$this' which allows the method to reference (i.e. "see") other variables and methods within the class. The variable '$this' auto-magically always refers to the current class wherever it is used.</p> <pre><code>class saySomething { var $helloWorld = 'hello world'; function sayHelloWorld($helloWorld) { //set myOutput to parameter value (if set), otherwise value of class var $myOutput = (isset($helloWorld)) ? $helloWorld : $this-&gt;helloWorld; echo $myOutput; } } $saySomething = new saySomething(); $saySomething-&gt;sayHelloWorld(); // Outputs 'hello world' from class definition $saySomething-&gt;sayHelloWorld('Hello world... again'); // Outputs 'Hello world... again' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload