Örtülü bir örnek örnek değişkenleri atamak için izin verilir?

2 Cevap php

Is it allowed to implicitly assign instance variables to an instance? That is, inside a method of a class that has no instance variables, can I just do this?

$this->foo = "foo";
$this->bar = "bar";

ve daha sonra sadece yine o diyorsun? PHP sadece bu durumda örnek değişkenleri yaratacak?

2 Cevap

Evet. PHP sadece başvurulan, ancak beyan edilmeyen hiçbir üye değişkenleri yaratacaktır. Ben sadece şu kodla test:

<?php
class Test {
    public function __construct() {
    }

    public function setMembers() {
        $this->foo = "fooValue";
        $this->bar = "barValue";
    }

    public function echoMembers() {
        echo $this->foo . "\n";
        echo $this->bar . "\n";
    }
}

$test = new Test();
$test->setMembers();
$test->echoMembers();
?>

Çalıştırıldığında, bu çıktılar:

fooValue
barValue

Hangi çalıştığını kanıtlıyor. Ben hala sınıfının üstündeki tüm sınıf üyesi değişkenleri bildirmek öneririz. Bu kodu muhafaza OO programcılar görmek için bekliyoruz budur.

Bilginize: PHP aşağıdaki sürümü ile benim test koştu:

$ php -version
PHP 5.2.8 (cli) (built: Feb  5 2009 21:21:13) 
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

Evet, sadece nesne üzerine yeni özellikler oluşturmak olacaktır.