0

I just found my out that my post is duplicate of another. Its because I was lacking keywords to search this. I am sorry. Here is the answer of my question. I have never thought getter and setter methods. https://stackoverflow.com/a/829898/1932414

How can I make a class and give class some variables to populate and process them in class?

example :

here is my class code :

class Classname{
    public function save(){
      //get the dynamically given vars and process them
    }
}


$class = new Classname();
$class->color = 'red';
$class->anothercolor = 'blue';
$class->muchcolor = 'blue';
$class->save();

and in the save function I want to make process of given variables. How can I be able to get the variables?

Community
  • 1
  • 1
T. Cem Yılmaz
  • 500
  • 9
  • 30

2 Answers2

1

You can simply access dynamic vars with $this

    public function save(){
          foreach($this as $prop => $val ){

              //make your action 
              echo $prop . '-'.  $val;
          }
    }
Denys Klymenko
  • 394
  • 5
  • 18
0
class Classname{
    public function save(){
        $color = $this->color;
        $anothercolor = $this->anothercolor;
        $muchcolor = $this->muchcolor;
        //do what you need to do
    }
}


$class = new Classname();
$class->color = 'red';
$class->anothercolor = 'blue';
$class->muchcolor = 'blue';
$class->save();

or

class Classname{
    public function save(){
        $colors = $this->colors;
        //do what you need to do
    }
}


$class = new Classname();
$class->colors = ['red', 'blue', 'yellow'];
$class->save();
fico7489
  • 7,931
  • 7
  • 55
  • 89