<?php
class test{
function foo(){
echo $this->abc;
}
}
$test = new test;
$test->abc = 'abc';
?>
Remeber that i don't declare开发者_如何学Python the variable abc, but i want to set $abc to 'abc'. How to do this Sorry because this is a dummy question
I would use the magic methods PHP supports. Basically I'd build a constructor which takes a a string as an argument.
<?php
class Test {
public $abc;
public function __construct($abc) {
$this->abc = $abc;
}
public function __toString() {
return $this->abc;
}
}
Then you can call the class and pass the data you want to it like this.
$myClass = new Test('abc');
echo $myClass;
Of course you have to echo it out so that the magic method __toString() gets called.
class test{
public function __construct() {
$this->abc = 'abc';
}
public function foo(){
echo $this->abc;
}
}
$test = new test;
$test->abc = 'abc';
$abc will be created as a public property of class test when the constructor is executed automatically when you instantiate the object
OR
class test{
$this->abc = 'abc';
public function foo(){
if (!isset($this->abc))
$this->abc = 'abc';
echo $this->abc;
}
}
$test = new test;
$test->abc = 'abc';
Will create a public property called $abc in the instance of class test when you call the foo method, if it doesn't already exist
Did you test it? It works, although I'm not sure it's such a good idea.
You can 'dynamicly create' properties and functions by overloading some magic functions of php. See this link for more information. Normally one would use the __construct function to create the variable when initializing the class (like Mark Baker and MAINERROR already suggested). This is imo the preferred way.
You can however overwrite (in your case) the __set function to handle the setting of inaccessible properties. But please keep in mind that overwriting and using these functions (except __construct) can get very confusing very fast.
Actually, this is already working. But it is a bad practice.
Normally you should do something like this:
class test {
private $abc;
public function foo() {
echo $this->abc;
}
public function getABC() {
return $this->abc;
}
public function setABC($abc) {
// You can also add some additionally checks
$this->abc = $abc;
}
}
Which makes:
$bar = new test;
$bar->setABC('abc');
$bar->foo();
Remember to make your class attributes ($abc) always private or protected. It's encapsulation that makes OOP so powerfull.
If you want to use dynamic variable names, so instead of $this->abc you want to set $this->cba you should use the magic methods __set and __get
More about magic methods can be found here:
http://php.net/manual/en/language.oop5.magic.php
精彩评论