Posso creare una classe PHP che non può avere proprietà aggiunte in modo dinamico in fase di esecuzione?

StackOverflow https://stackoverflow.com/questions/8924163

  •  30-10-2019
  •  | 
  •  

Domanda

Prendi questa lezione per un esempio:

<?php

class Person
{
    private $name = null;
    private $dob = null;

    public function __construct($name, $dob)
    {
        $this->name = $name;
        $this->dob = $dob;
    }
}

$potts = new Person('Matt', '01/01/1987');
var_dump($potts);

$potts->job = 'Software Developer'; // new dynamic property
var_dump($potts);

var_dump(get_object_vars($potts));

L'output è il seguente:

object(Person)#1 (2) {
  ["name":"Person":private]=>
  string(4) "Matt"
  ["dob":"Person":private]=>
  string(10) "01/01/1987"
}

object(Person)#1 (3) {
  ["name":"Person":private]=>
  string(4) "Matt"
  ["dob":"Person":private]=>
  string(10) "01/01/1987"
  ["job"]=>
  string(18) "Software Developer"
}

array(1) {
  ["job"]=>
  string(18) "Software Developer"
}

È possibile l'aggiunta di proprietà dinamiche? È possibile ottenere un elenco di proprietà definite dalla classe? (cioè non dinamico, proprietà aggiunte in tempo run-time)

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top