durian
durian

Reputation: 520

var inside var in oop php

Im just a biginner in object oriented programming and currently learning object oriented php and i have got a bit confused with including a variable inside a variable inside of a class, usually i would do something like:

$div_content="some content";
$div = '<div>'.$div_content.'</div>';

but when trying to do it like this, i get an error:

class SomeClass{

private $div_content ="some content";
public $div='<div>'.$div_content.'</div>';

function __construct(){

echo $this->div;

}

}

Can some one please help me understand what im doing wrong here? thanks in advance.

Upvotes: 0

Views: 79

Answers (4)

rm-vanda
rm-vanda

Reputation: 3168

Variables are treated slightly different in classes -- and a construction like yours or maja's --- if it works -- is bound to cause -- "problems"

Try something like this, instead:

class SomeClass{ 

private $div_content; 
public $div; 

function __construct($content){ 

$this->div_content = $content; 
$this->makeDiv(); 

}

function makeDiv(){

echo "<div>".$this->div_content."</div>"; 

}
} 

Of course, there are a dozen ways to do it, but I would advise you not to define the variables in the beginning.

Upvotes: 1

sibbl
sibbl

Reputation: 3229

You should look into getter and setter methods. You just want to get something, so use a getter method for $div, called getDiv

class SomeClass{
  private $div_content = "some content";

  public function getDiv() {
    return '<div>'.$this->div_content.'</div>';
  }

  function __construct(){
    echo $this->getDiv();
  }
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

When defining properties on a class like that, you may only use a specific value. There can be no calculations or operations. For example, you can't have public $five = 2+3;, it won't work.

Instead, you can define these properties in the constructor of your function.

Upvotes: 1

Sam
Sam

Reputation: 2970

 function __construct(){
  $this->div = '<div>'.$this->div_content.'</div>';
  echo $this->div;
 }

You can define only static values on declarations, use the __construct() for it

Upvotes: 3

Related Questions