PHP의 특성 사용법 및 예

silencement
풀어 주다: 2023-04-08 11:24:01
앞으로
4740명이 탐색했습니다.

PHP의 특성 사용법 및 예

PHP는 단일 상속 언어입니다. PHP 5.4 특성이 등장하기 전에는 PHP 클래스가 두 기본 클래스의 속성이나 메서드를 동시에 상속할 수 없었습니다. 이 문제를 해결하기 위해 PHP는 특성 기능을 도입했습니다. (Trait와 Go 언어의 결합 기능은 다소 유사합니다.)

사용법: 클래스에서 use 키워드를 사용하여 결합할 Trait 이름을 선언하고, 특정 Trait의 선언은 trait 키워드를 사용하며, Trait을 지정할 수 없습니다. 직접 인스턴스화되었습니다.

<?php
trait Drive {
    public $carName = &#39;BMW&#39;;
    public function driving() {
        echo "driving {$this->carName}\n";
    }
}
 
class Person {
    public function age() {
        echo "i am 18 years old\n";
    }
}
 
class Student extends Person {
    use Drive;
    public function study() {
        echo "Learn to drive \n";
    }
}
 
$student = new Student();
$student->study();  //输出:Learn to drive 
$student->age();    //输出:i am 18 years old
$student->driving();//输出:driving BMW
로그인 후 복사

결론:

Student 클래스는 Person을 상속하고 age 메소드를 갖습니다.

Drive를 결합하여 운전 메소드와 carName 속성을 갖습니다.

Trait, 기본 클래스, 이 클래스에 같은 이름을 가진 속성이나 메서드가 있으면 결국 어떤 것이 유지되나요? 다음 코드로 테스트해 보세요.

<?php
 
trait Drive {
    public function hello() {
        echo "hello 周伯通\n";
    }
    public function driving() {
        echo "周伯通不会开车\n";
    }
}
 
class Person {
    public function hello() {
        echo "hello 大家好\n";
    }
    public function driving() {
        echo "大家都会开车\n";
    }
}
 
class Student extends Person {
    use Drive;//trait 的方法覆盖了基类Person中的方法,所以Person中的hello 和driving被覆盖
    public function hello() {
        echo "hello 新学员\n";//当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,所以此处hello会覆盖trait中的
        hello
    }
}
 
$student = new Student();
$student->hello();    //输出:hello 新学员
$student->driving();  //输出:周伯通不会开车
로그인 후 복사

결론: 메서드나 속성의 이름이 같은 경우 현재 클래스의 메서드가 특성의 메서드를 재정의하고 특성의 메서드가 기본 클래스의 메서드를 재정의합니다.

여러 특성을 결합하려면 특성 이름을 쉼표로 구분하세요.

use Trait1, Trait2;

여러 특성에 동일한 이름의 메서드나 속성이 포함되어 있으면 어떻게 되나요? 대답은 여러 개의 결합된 특성에 동일한 이름의 속성이나 메서드가 포함된 경우 충돌을 해결하기 위해 명시적으로 선언해야 하며 그렇지 않으면 치명적인 오류가 발생한다는 것입니다.

<?php
trait Trait1 {
    public function hello() {
        echo "Trait1::hello\n";
    }
    public function hi() {
        echo "Trait1::hi\n";
    }
}
 
trait Trait2 {
    public function hello() {
        echo "Trait2::hello\n";
    }
    public function hi() {
        echo "Trait2::hi\n";
    }
}
 
class Class1 { 
    use Trait1, Trait2;
}
 
//输出:Fatal error:  Trait method hello has not been applied, because there are collisions with other trait
 methods on Class1 in
로그인 후 복사

대신of와 연산자를 사용하여 충돌을 해결하세요. 대신에 한 메서드를 사용하여 다른 메서드를 대체하고 as는 해당 메서드에 별칭을 제공합니다.

<?php
trait Trait1 {
    public function hello() {
        echo "Trait1::hello \n";
    }
    public function hi() {
        echo "Trait1::hi \n";
    }
}
trait Trait2 {
    public function hello() {
        echo "Trait2::hello\n";
    }
    public function hi() {
        echo "Trait2::hi\n";
    }
}
class Class1 {
    use Trait1, Trait2 {
        Trait2::hello insteadof Trait1;
        Trait1::hi insteadof Trait2;
    }
}
 
class Class2 {
    use Trait1, Trait2 {
        Trait2::hello insteadof Trait1;
        Trait1::hi insteadof Trait2;
        Trait2::hi as hei;
        Trait1::hello as hehe;
    }
}
 
$Obj1 = new Class1();
$Obj1->hello();
$Obj1->hi();
echo "\n";
$Obj2 = new Class2();
$Obj2->hello();
$Obj2->hi();
$Obj2->hei();
$Obj2->hehe();
로그인 후 복사

Output

Trait2::hello
Trait1::hi 
 
Trait2::hello
Trait1::hi 
Trait2::hi
Trait1::hello
로그인 후 복사
<?php
trait Hello {
    public function hello() {
        echo "hello,我是周伯通\n";
    }
}
class Class1 {
    use Hello {
        hello as protected;
    }
}
class Class2 {
    use Hello {
        Hello::hello as private hi;
    }
}
$Obj1 = new Class1();
$Obj1->hello(); # 报致命错误,因为hello方法被修改成受保护的
 
$Obj2 = new Class2();
$Obj2->hello(); # 输出: hello,我是周伯通,因为原来的hello方法仍然是公共的
$Obj2->hi();  # 报致命错误,因为别名hi方法被修改成私有的
로그인 후 복사
Uncaught Error: Call to protected method Class1::hello() from context &#39;&#39; in D:\web\mytest\p.php:18
로그인 후 복사

Trait도 결합할 수 있습니다. Trait은 추상 메서드, 정적 속성 및 정적 메서드를 지원합니다.

<?php
trait Hello {
    public function sayHello() {
        echo "Hello 我是周伯通\n";
    }
}
 
trait World {
    use Hello;
    public function sayWorld() {
        echo "hello world\n";
    }
    abstract public function getWorld();
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c\n";
    }
    public static function doSomething() {
        echo "Doing something\n";
    }
}
 
class HelloWorld {
    use World;
    public function getWorld() {
        return &#39;do you get World ?&#39;;
    }
}
 
$Obj = new HelloWorld();
$Obj->sayHello();
$Obj->sayWorld();
echo $Obj->getWorld() . "\n";
HelloWorld::doSomething();
$Obj->inc();
$Obj->inc();
로그인 후 복사

Output

Hello 我是周伯通
hello world
do you get World ?
Doing something12
로그인 후 복사


위 내용은 PHP의 특성 사용법 및 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:www.liqingbo.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!