>  기사  >  백엔드 개발  >  PHP 객체 지향의 일부 메서드 및 함수 응용 프로그램에 대한 코드

PHP 객체 지향의 일부 메서드 및 함수 응용 프로그램에 대한 코드

不言
不言원래의
2018-05-04 17:01:251400검색

이 기사는 주로 참조 가치가 있는 PHP 객체 지향에 대한 몇 가지 지식 포인트를 소개합니다. 이제 필요한 친구들이 참조할 수 있습니다.

1. __construct:

내장 생성자 객체가 생성되면 자동으로 호출됩니다. 다음 코드를 참조하세요.

<?php
class ConstructTest {
    private $arg1;
    private $arg2;
 
    public function __construct($arg1, $arg2) {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
        print "__construct is called...\n";
    }
    public function printAttributes() {
        print &#39;$arg1 = &#39;.$this->arg1.&#39; $arg2 = &#39;.$this->arg2."\n";
    }
}
$testObject = new ConstructTest("arg1","arg2");
$testObject->printAttributes();

실행 결과는 다음과 같습니다.

Stephens-Air:Desktop$ php Test.php 
__construct is called...
$arg1 = arg1 $arg2 = arg2

2. parent:

는 하위 클래스의 상위 클래스에 있는 메서드를 직접 호출하는 데 사용되며 해당 기능은 Java의 super와 동일합니다.

<?php
class BaseClass {
    protected $arg1;
    protected $arg2;
 
    function __construct($arg1, $arg2) {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
        print "__construct is called...\n";
    }
    function getAttributes() {
        return &#39;$arg1 = &#39;.$this->arg1.&#39; $arg2 = &#39;.$this->arg2;
    }
}
 
class SubClass extends BaseClass {
    protected $arg3;
 
    function __construct($baseArg1, $baseArg2, $subArg3) {
        parent::__construct($baseArg1, $baseArg2);
        $this->arg3 = $subArg3;
    }
    function getAttributes() {
        return parent::getAttributes().&#39; $arg3 = &#39;.$this->arg3;
    }
}
$testObject = new SubClass("arg1","arg2","arg3");
print $testObject->getAttributes()."\n";

의 실행 결과는 다음과 같습니다.

Stephens-Air:Desktop$ php Test.php 
__construct is called...
$arg1 = arg1 $arg2 = arg2 $arg3 = arg3

3.self:

클래스 내에서 이 클래스의 정적 멤버 및 정적 메서드의 접두사 수정을 호출하고 이를 비정적 멤버 변수 및 함수에 사용합니다. .

<?php
class StaticExample {
    static public $arg1 = "Hello, This is static field.\n";
    static public function sayHello() {
        print self::$arg1;
    }
}
 
print StaticExample::$arg1;
StaticExample::sayHello();

실행 결과는 다음과 같습니다.

Stephens-Air:Desktop$ php Test.php 
Hello, This is static field.
Hello, This is static field.

4.static:

여기서 소개하는 static 키워드는 주로 PHP 5.3 이상에서 새로 추가된 지연된 정적 바인딩 기능에 사용됩니다. 코드와 중요한 의견을 살펴보시기 바랍니다.

<?php
abstract class Base {
    public static function getInstance() {
        //这里的new static()实例化的是调用该静态方法的当前类。
        return new static();
    }
    abstract public function printSelf();
}
 
class SubA extends Base {
    public function printSelf() {
        print "This is SubA::printSelf.\n";
    }
}
 
class SubB extends Base {
    public function printSelf() {
        print "This is SubB::printSelf.\n";
    }
}
 
SubA::getInstance()->printSelf();
SubB::getInstance()->printSelf();

실행 결과는 다음과 같습니다.

Stephens-Air:Desktop$ php Test.php 
This is SubA::printSelf.
This is SubB::printSelf.

static 키워드는 인스턴스화에만 사용할 수 없습니다. self 및 parent와 마찬가지로 static은 비정적 컨텍스트에서도 정적 메서드 호출에 대한 식별자로 사용할 수 있습니다. 이 시나리오에서 self는 여전히 현재 메서드가 있는 클래스를 나타냅니다. 다음 코드를 참조하세요.

<?php
abstract class Base {
    private $ownedGroup;
    public function __construct() {
        //这里的static和上面的例子一样,表示当前调用该方法的实际类。
        //需要另外说明的是,这里的getGroup方法即便不是静态方法,也会得到相同的结果。然而倘若
        //getGroup真的只是普通类方法,那么这里还是建议使用$this。
        $this->ownedGroup = static::getGroup();
    }
    public function printGroup() {
        print "My Group is ".$this->ownedGroup."\n";
    }
    public static function getInstance() {
        return new static();
    }
    public static function getGroup() {
        return "default";
    }
}
 
class SubA extends Base {
}
 
class SubB extends Base {
    public static function getGroup() {
        return "SubB";
    }
}
 
SubA::getInstance()->printGroup();
SubB::getInstance()->printGroup();

실행 결과는 다음과 같습니다.

Stephens-Air:Desktop$ php Test.php 
My Group is default
My Group is SubB

5. __destruct:

소멸자 메서드의 역할은 생성 메서드 __construct와 정확히 반대입니다. 객체는 가비지 수집기에 의해 수집됩니다. 이 방법을 사용하여 필요한 정리 작업을 수행할 수 있습니다.

<?php
class TestClass {
    function __destruct() {
        print "TestClass destructor is called.\n";
    }
}
 
$testObj = new TestClass();
unset($testObj);
print "Application will exit.\n";

실행 결과는 다음과 같습니다:

Stephens-Air:Desktop$ php Test.php 
TestClass destructor is called.
Application will exit.

6 __clone:

     在PHP 5之后的版本中,对象之间的赋值为引用赋值,即赋值后的两个对象将指向同一地址空间,如果想基于对象赋值,可以使用PHP提供的clone方法。该方法将当前对象浅拷贝之后的副本返回,如果想在clone的过程中完成一些特殊的操作,如深拷贝,则需要在当前类的声明中实现__clone方法,该方法在执行clone的过程中会被隐式调用。另外需要格外注意的是,__clone方法是作用再被拷贝的对象上,即赋值后的对象上执行。

<?php
class InnerClass {
    public $id = 10;
    public function printSelf() {
        print &#39;$id = &#39;.$this->id."\n";
    }
}
 
class OuterClass {
    public $innerClass;
    public function __construct() {
        $this->innerClass = new InnerClass();
    }
    public function __clone() {
        $this->innerClass = clone $this->innerClass;
        print "__clone is called.\n";
    }
}
 
$outerA = new OuterClass();
print "Before calling to clone.\n";
$outerB = clone $outerA;
print "After calling to clone.\n";
$outerA->innerClass->id = 20;
print "In outerA: ";
$outerA->innerClass->printSelf();
print "In outerB: ";
$outerB->innerClass->printSelf();

 运行结果如下:

Stephens-Air:Desktop$ php Test.php 
Before calling to clone.
__clone is called.
After calling to clone.
In outerA: $id = 20
In outerB: $id = 10

7. const:

    PHP5可以在类中定义常量属性。和全局常量一样,一旦定义就不能改变。常量属性不需要像普通属性那样以$开头,按照惯例,只能用大写字母来命名常量。另外和静态属性一样,只能通过类而不能通过类的实例访问常量属性,引用常量时同样也不需要以$符号作为前导符。另外常量只能被赋值为基础类型,如整型,而不能指向任何对象类型。

<?php
class TestClass {
    const AVAILABLE = 0;
}
print "TestClass::AVAILABLE = ".TestClass::AVAILABLE."\n";

运行结果如下:

0Stephens-Air:Desktop$ php Test.php 
TestClass::AVAILABLE = 0

相关推荐:

PHP面向对象 静态延迟绑定static::

浅谈PHP面向对象编程

위 내용은 PHP 객체 지향의 일부 메서드 및 함수 응용 프로그램에 대한 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.