PHP 5 : const 대 정적
PHP 5에서 using const
과 static
? 의 차이점은 무엇 입니까?
언제 각각 적절한가요? 그리고 어떤 역할을하는 수행 public
, protected
그리고 private
놀이 - 어떤 경우에?
클래스의 맥락에서 정적 변수는 객체가 아닌 클래스 범위에 있지만 const와 달리 값을 변경할 수 있습니다.
class ClassName {
static $my_var = 10; /* defaults to public unless otherwise specified */
const MY_CONST = 5;
}
echo ClassName::$my_var; // returns 10
echo ClassName::MY_CONST; // returns 5
ClassName::$my_var = 20; // now equals 20
ClassName::MY_CONST = 20; // error! won't work.
공개, 보호 및 개인은 const (항상 공개)의 측면에서 관련이 없습니다. 정적 변수를 포함하여 클래스 변수에만 유용합니다.
- 공용 정적 변수는 ClassName :: $ variable을 통해 어디서나 액세스 할 수 있습니다.
- 보호 된 정적 변수는 클래스를 정의하거나 ClassName :: $ variable을 통해 클래스를 확장하여 액세스 할 수 있습니다.
- 전용 정적 변수는 ClassName :: $ variable을 통해 정의 클래스에서만 액세스 할 수 있습니다.
편집 : PHP 7.1.0은 클래스 상수의 가시성을 지정하는 지원을 도입했습니다 .
마지막으로해야 할 점은 const가 항상 정적이고 공개적이라는 것입니다. 즉, 클래스 내에서 다음과 같이 const에 액세스 할 수 있습니다.
class MyClass
{
const MYCONST = true;
public function test()
{
echo self::MYCONST;
}
}
수업 밖에서 다음과 같이 액세스하십시오.
echo MyClass::MYCONST;
상수 는 상수 일뿐입니다. 선언 한 후에는 값을 변경할 수 없습니다.
정적 변수는 클래스의 인스턴스를 만들지 않고도 액세스 할 수 있으므로 클래스의 모든 인스턴스간에 공유됩니다.
또한 함수에 정적 로컬 변수 가있을 수 있습니다 ( 함수의 첫 번째 실행시) 한 번만 선언되고 함수 호출간에 해당 값을 저장할 수 있습니다. 예 :
function foo()
{
static $numOfCalls = 0;
$numOfCalls++;
print("this function has been executed " . $numOfCalls . " times");
}
클래스 상속에 대해 이야기 할 때 self
및 static
키워드 를 사용하여 다른 범위의 상수 또는 변수를 구별 할 수 있습니다 . 다음에 액세스하는 방법을 보여주는이 예제를 확인하십시오.
class Person
{
static $type = 'person';
const TYPE = 'person';
static public function getType(){
var_dump(self::TYPE);
var_dump(static::TYPE);
var_dump(self::$type);
var_dump(static::$type);
}
}
class Pirate extends Person
{
static $type = 'pirate';
const TYPE = 'pirate';
}
그리고 나서 :
$pirate = new Pirate();
$pirate::getType();
또는:
Pirate::getType();
산출:
string(6) "person"
string(6) "pirate"
string(6) "person"
string(6) "pirate"
즉 self::
, 정적 속성과 상수가 호출되는 동일한 범위 (이 경우 Person
수퍼 클래스)의 static::
상수를 나타내며 런타임의 범위 (이 경우 Pirate
하위 클래스) 의 속성과 상수에 액세스합니다 .
php.net에서 정적 바인딩에 대한 자세한 내용 은 여기를 참조하십시오 .
또한 여기 및 여기 에서 다른 질문에 대한 답변을 확인 하십시오 .
클래스 메서드 나 속성을 정적으로 선언하면 클래스를 인스턴스화하지 않고도 액세스 할 수 있습니다.
클래스 상수는 일반 상수와 같으며 런타임에 변경할 수 없습니다. 이것은 또한 const를 사용할 유일한 이유이기도합니다.
개인, 공개 및 보호는 누가 어떤 매개 변수 / 방법에 액세스 할 수 있는지를 설명하는 액세스 수정 자입니다.
공용은 다른 모든 개체에 액세스 할 수 있음을 의미합니다. 비공개는 인스턴스화 된 클래스 만 액세스 할 수 있음을 의미합니다. 보호는 인스턴스화 된 클래스 및 파생 클래스에 액세스 할 수 있음을 의미합니다.
정적 멤버, 상수 변수 및 액세스 수정 자 (비공개, 공개 및 보호)에 대해 지금까지 배운 것들이 있습니다. 일정한
정의
이름처럼 상수 변수의 값은 변경할 수 없습니다. 상수는 $ 기호를 사용하여 선언하거나 사용하지 않는다는 점에서 일반 변수와 다릅니다.
값은 변수, 속성, 수학 연산 결과 또는 함수 호출이 아닌 상수 식이어야합니다.
참고 : 변수 값은 키워드가 될 수 없습니다 (예 : self, parent 및 static).
PHP에서 상수 선언
<?php
class constantExample{
const CONSTANT = 'constant value'; //constant
}
?>
Constant의 범위는 전역 적이며 자체 키워드를 사용하여 액세스 할 수 있습니다
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT . "\n";
$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::CONSTANT."\n"; // As of PHP 5.3.0
?>
공전
정의
Static keyword can be used for declaring a class, member function or a variable.Static members in a class is global can be accessed using a self keyword as well.Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can). If no visibility declaration ( public, private, protected ) is used, then the property or method will be treated as if it was declared as public.Because static methods are callable without an instance of the object created.
Note : the pseudo-variable $this is not available inside the method declared as static.Static properties cannot be accessed through the object using the arrow operator ->
As of PHP 5.3.0, it's possible to reference the class using a variable. The >variable's value cannot be a keyword (e.g. self, parent and static).
Static property example
<?php
class Foo
{
public static $my_static = 'foo'; //static variable
public static function staticValue() { //static function example
return self::$my_static; //return the static variable declared globally
}
}
?>
Accessing static properties and functions example
<?php
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
Public, private , protected (A.K.A access modifiers)
Before reading the definition below , read this Article about Encapsulation .It will help you to understand the concept more deeply
Tutorials point link about encapsulation
Definition
Using private , public , protected keywords you can control access to the members in a class. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
Example
<?php
class Example{
public $variable = 'value'; // variable declared as public
protected $variable = 'value' //variable declared as protected
private $variable = 'value' //variable declared as private
public function functionName() { //public function
//statements
}
protected function functionName() { //protected function
//statements
}
private function functionName() { //private function
//statements
}
}
?>
Accessing the public, private and protected members example
Public variable's can be accessed and modified from outside the class or inside the class. But You can access the private and protected variables and functions only from inside the class , You can't modify the value of protected or Public members outside the class.
<?php
class Example{
public $pbVariable = 'value';
protected $protVariable = 'value';
private $privVariable = 'value';
public function publicFun(){
echo $this->$pbVariable; //public variable
echo $this->$protVariable; //protected variable
echo $this->privVariable; //private variable
}
private function PrivateFun(){
//some statements
}
protected function ProtectedFun(){
//some statements
}
}
$inst = new Example();
$inst->pbVariable = 'AnotherVariable'; //public variable modifed from outside
echo $inst->pbVariable; //print the value of the public variable
$inst->protVariable = 'var'; //you can't do this with protected variable
echo $inst->privVariable; // This statement won't work , because variable is limited to private
$inst->publicFun(); // this will print the values inside the function, Because the function is declared as a public function
$inst->PrivateFun(); //this one won't work (private)
$inst->ProtectedFun(); //this one won't work as well (protected)
?>
For more info read this php documentation about visibility Visibility Php Doc
References : php.net
I hope you understood the concept. Thanks for reading :) :) Have a good one
So to recap on @Matt great answer:
if the property you need should not be changed, then a constant is the the proper choice
if the property you need is allowed to be changed, use static instead
Example:
class User{
private static $PASSWORD_SALT = "ASD!@~#asd1";
...
}
class Product{
const INTEREST = 0.10;
...
}
Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.
참고URL : https://stackoverflow.com/questions/1685922/php-5-const-vs-static
'IT' 카테고리의 다른 글
변수에 표준 오류를 저장하는 방법 (0) | 2020.06.02 |
---|---|
C # 또는 VB.NET에서 할 수없는 MSIL에서 무엇을 할 수 있습니까? (0) | 2020.06.02 |
C ++ 맵에서 insert vs emplace vs operator [] (0) | 2020.06.02 |
ExpandoObject, DynamicObject 및 dynamic의 차이점 (0) | 2020.06.02 |
파일 포인터 (FILE * fp)를 파일 디스크립터 (int fd)로 어떻게 변환 할 수 있습니까? (0) | 2020.06.02 |