Home > Article > Backend Development > PHP function scope and access permissions
PHP functions have scope and access permissions, which determine the visibility of variables and functions. Scope includes local (only within the function), global (inside and outside the function), and superglobal (any scope). Access rights include public (access from anywhere), protected (access only to classes and subclasses), and private (access within the class only). In actual combat, the private variables of the shopping cart class are only accessible within the class, while the public methods can be called from the outside, reflecting the application of scope and access rights.
Scope and access permissions of PHP functions
Scope of functions
The scope of a function determines the scope of variables available in the code. There are three types of scopes in PHP:
Variable scope example
<?php function myFunction() { $localVariable = "Local"; // 局部变量 echo $localVariable; // 在函数内部可用 } $globalVariable = "Global"; // 全局变量 myFunction(); echo $globalVariable; // 在函数外部可用 ?>
Access permissions
Function access permissions control access to functions by external code . There are three types of access rights in PHP:
Access permission example
<?php class MyClass { public function publicMethod() { // 可从任何地方访问 } protected function protectedMethod() { // 可从类及其子类中访问 } private function privateMethod() { // 仅可从类内部访问 } } $myClass = new MyClass(); $myClass->publicMethod(); // 可访问 $myClass->protectedMethod(); // 可访问(类外部子类中) $myClass->privateMethod(); // 错误,不可访问 ?>
Practical case
Create a simple shopping cart class to display the scope and access rights.
<?php class Cart { private $items = []; public function addItem($item) { $this->items[] = $item; // 局部变量 $item 可在此处访问 } public function getItems() { return $this->items; // 局部变量 $items 可在此处访问 } } $cart = new Cart(); $cart->addItem("苹果"); $cart->addItem("香蕉"); print_r($cart->getItems()); // 输出购物车中的物品 ?>
In this example:
$items
The variable is private in the Cart
class and can only be accessed within the class. The addItem
and getItems
methods are public and accessible from external code. The above is the detailed content of PHP function scope and access permissions. For more information, please follow other related articles on the PHP Chinese website!