PHP Array values and concatenation problem
I have a short title and message that I want to show, defining the following:
class A {
public $name = 'Mark';
public $entry = array(
'title' => 'Some title',
'message' => 'Hi '.$name
);
// Constructor
public function __construct() {}
// Some other functions
}
This isn't working.
开发者_StackOverflow社区Can someone explain why? Should I go for separate variables instead or is there a better way? Thanks for your time.
EDIT
You are trying to pull that off in property declaration of a Class, aren't you? Property declarations happen during COMPILE-TIME and can only accept values, not operations that require RUN-TIME to happen and concatenation definitely is a run-time operation... Put that line into your constructor method instead.
class A
{
public $name = 'Mark';
public $entry = array("test");
public $var1 = someFunct(); // WRONG, ITS AN OPERATION and REQUIRES RUNTIME
public $var2 = 1 + 2; // WRONG, ITS AN OPERATION and REQUIRES RUNTIME
public $var3 = CLASS_NAME::SOME_CONSTANT_OR_PROPERTY_HERE; // WORKS, CONSTANTS ARE DETECTED IN COMPILE-TIME
public $var4 = $anythingWithDollarSign; // WRONG, SYNTAX ERROR, REQUIRES RUNTIME
public function __construct() {
$this->entry = array( 'title' => 'Some title', 'message' => 'Hi ' . $this->name );
}
}
in classes, you can only declare variables that consist of a static value, and not a dynamic value such as "name" . $name
.
What you would have to do is concat in the constructor, (That's why its there):
class A
{
public $name = 'Mark';
public $entry = array(
'title' => 'Some title',
'message' => 'Hi %s'
);
// Constructor
public function __construct()
{
$this->entry["message"] = sprintf($this->entry["message"],$this->name);
}
}
精彩评论