List private properties

Asked

Viewed 92 times

2

I have the following class:

class Orcamento{

    private $valor;
    private $itens;

    public function __construct($valor){
        $this->valor = $valor;
        $this->itens = [];
    }

    public function __get($property){
        return $this->$property;
    }

    public function __set($property, $value){

        if($property === "itens")
            throw new \Exception("Utilize o método 'addItem' para alterar esta propriedade");

        $this->$property = $value;
    }

    public function addItem(Item $item){
        $this->itens[] =  $item;
    }
}

This class has two private properties, a getter and Setter constructor and methods. When I assign a value to a property that does not exist, immediately a new public property is created. As can be seen in the example below:

$orcamento = new Orcamento(600);

$orcamento->teste = "teste";

echo $orcamento->teste;

The above expression will print the string "test".

My question is:

  1. Is there any method that lists private properties?
  2. Is there any way to prevent the creation of methods and/or properties in a class?
  3. There are access modifiers for class and not only for methods and properties?
  • What would that be get_class within the method __set? What is meant by "access modifiers for classes"?

  • It was a test for the get_class_vars() method. But it lists only public properties. When I talk about access modifiers for classes, I comment on the possibility or not of adding a modifier to the class creation so that it cannot be changed. I believe that this does not exist, this part would be just a doubt

1 answer

2


Is there any method that lists private properties?

The simplest way is with get_object_vars(). If you want to filter the toilets you can use reflection:

new ReflectionClass($this)->getProperties(ReflectionProperty::IS_PRIVATE);

I put in the Github for future reference.

A tremendous gambit. If you are going to use things like this you should not create a class, a array associative seems to be more the case, something that people are forgetting that exists.

Is there any way to prevent the creation of methods and/or properties in a class?

Not by language, the purpose of language is (or was) to give flexibility unreliability and robustness (now they are changing the philosophy of language but too late, can only truly breaking compatibility with all that it was).

You can use a technique like the one you used to force call the method addItem(), check if a private variable equivalent to the property exists to assume a value. A beautiful gambiarra.

There are access modifiers for class and not only for methods and properties?

There are, but not the same modifiers, they serve very different purposes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.