Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-style Variable initialization in PHP

Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?

like image 980
Jhourlad Estrella Avatar asked Dec 29 '22 11:12

Jhourlad Estrella


2 Answers

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:\xampp\htdocs\scope.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.

like image 150
mauris Avatar answered Jan 11 '23 17:01

mauris


In PHP there are static, local, private, public, and protected class variables.

However, in the PHP OOP implementation things are a little different: the manual will help you:

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private.

Furthermore, have a look at the static keyword documentation.

You'll be able to read more about normal variables and their scope here: http://php.net/manual/en/language.variables.scope.php:

For the most part all PHP variables only have a single scope.

I hope the links will be able to explain it to you better than I did ;-)

like image 42
phidah Avatar answered Jan 11 '23 19:01

phidah