I don t know about C++ but there s how PHP works about:
For Function scopes:
<?php
$b = 6;
function testFunc($a){
echo $a. - .$b;
}
function testFunc2($a){
global $b;
echo $a. - .$b;
}
testFunc(3);
testFunc2(3);
?>
The output is
3-
3-6
Code inside functions can only be accessed variables outside functions using the global keyword. See http://php.net/manual/en/language.variables.scope.php
As for classes:
<?php
class ExampleClass{
private $private_var = 40;
public $public_var = 20;
public static $static_var = 50;
private function classFuncOne(){
echo $this->private_var. - .$this->public_var; // outputs class variables
}
public function classFuncTwo(){
$this->classFuncOne();
echo $private_var. - .$public_var; // outputs local variable, not class variable
}
}
$myobj = new ExampleClass();
$myobj->classFuncTwo();
echo ExampleClass::$static_var;
$myobj->classFuncOne(); // fatal error occurs because method is private
?>
Output would be:
40-20
-
50
Fatal error: Call to private method ExampleClass::classFuncOne() from context in C:xampphtdocsscope.php on line 22
One note to take: PHP does not have variable initialization, although variables are said to be set or not set. When a variable is set, it has been assigned with a value. You can use the unset
to remove the variable and its value. A not set variable is equivalent to false, and if you use it with all errors output, you will see a E_NOTICE error.