Initializing C-Style Variables 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 is their volume demonstrated inside and outside the class and inside the functions?

+4
source share
3 answers

I do not know about C ++, but where PHP works:

For function areas:

<?php $b = 6; function testFunc($a){ echo $a.'-'.$b; } function testFunc2($a){ global $b; echo $a.'-'.$b; } testFunc(3); testFunc2(3); ?> 

Output signal

3-
3-6

Internal code functions can only be accessed by variables outside functions using the global keyword. See http://php.net/manual/en/language.variables.scope.php

Regarding 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:

40-20
-
fifty
Fatal error: calling the private method ExampleClass :: classFuncOne () from the context '' in C: \ xampp \ htdocs \ scope.php on line 22

One note: PHP does not have variable initialization, although it is believed that the variables are set or not set. When a variable is set, it is assigned a value. You can use unset to remove a variable and its value. An undefined variable is equivalent to false, and if you use it with all error outputs, you will see an E_NOTICE error.

+5
source

PHP has class variables static, local, private, public and protected.

However, things are slightly different in the PHP OOP implementation: the guide will help you:

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

Also, see the static keyword documentation .

You can learn more about normal variables and their scope here: http://php.net/manual/en/language.variables.scope.php :

For the most part, all PHP variables have only one scope.

I hope the links can explain this to you better than me -)

+4
source

yes, PHP 5 incldude static variables and visibility in the class.

 class MyClass { public static $my_static = 'foo'; public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; public function staticValue() { return self::$my_static; } function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private 
+1
source

All Articles