Dherya Dherya - 8 months ago 38
PHP Question

Assigning values to undeclared properties

I don't understand a concept of class in . I could be wrong.

I looked at a WordPress plugin. The class was defined and the properties of class wasn't created only functions were created.

Consider this example

class a
public function show(){
echo "hello";
$this->something = "xyz" ;
// What is this? How can "something" can be used here;
// as it is not defined in the class?

Then an object of that class was created in another file.

$obj = new a();
$obj->anothersomething = "abc"; // is it possible?

Enlighten me please.

My question is: Can we assign a value to undeclared property of a class?


Default class visibility is public.
However, it is good practice to explicitly declare class method with it's visibility.

class Foo
    public function a() {}
    protected function b() {}
    private function c() {}

As @SougataBose mentioned, I'd suggest you running through PHP OOP course


When it comes to properties - yes. It is possible to create them dynamically. Again, as a good practice, it is recommended to declare all properties in class body.