我对PhP oop很新。我想在这里做一个小项目是我的代码:
class Language {
public $hello;
public $greetings;
public function english(){
echo $this->hello = "Hello" . "<br>";
echo $this->greetings = "Greetings" . "<br>";
}
public function british(){
echo $this->hello = "Ello there mate!" . "<br>";
echo $this->greetings = "Oi ya cheeky bugger" . "<br>";
}
}
$language = new Language;
echo $language->english();
echo $language->british();
如何回显变量 $ hello ,但只能从1个函数中回显?我真的不明白我想在这里做的。
基本上我想从 english()中获取 $ hello 并在
中回显<p></p>
或者那些行
有人能指出我正确的方向吗?
答案 0 :(得分:1)
只需在方法中设置它们,然后直接从对象访问变量:
sshoskar@oskog97:~$ ./test.py
* * * * *** *** **** * * *
* * * * * * * * * * * * *
** * * * * * * * * * ** *
* * * * * * * *** **** * * * *
* ** * * * * * * * * **
* * * * * * * * * * * *
* * *** *** *** * * * *
答案 1 :(得分:1)
您需要设置属性,然后再调用它。我认为你的订单混乱了。
public function english(){
$this->hello = "Hello" . "<br>";
$this->greetings = "Greetings" . "<br>";
}
$language->english();
echo $language->hello;
也许这有点模块化......
class Language {
public $hello;
public $greetings;
public function english(){
$this->hello = "Hello" . "<br>";
$this->greetings = "Greetings" . "<br>";
}
public function british(){
$this->hello = "Ello there mate!" . "<br>";
$this->greetings = "Oi ya cheeky bugger" . "<br>";
}
}
$language = new Language;
$language->english();
echo $language->hello;
答案 2 :(得分:0)
我试图给你一个例子,首先,保护你的专业,给他们一个不同的可见度,而不是公共&#34;并且不要在你的类中硬编码这个属性的值,也许有一天你想要改变他们的内容,你必须修改类,而不是使用一些方法来改变他们的内容。你可能想知道,为什么我的不同的可见性属性?好吧,从课外,我可以将这些属性的内容(如果它们具有公共可见性)更改为我想要的任何值和数据类型,这样我就可以打破你的程序流程。
class Language
{
protected $hello = '';
protected $greetings = '';
public function setEnglish($hello = '', $greetings = '')
{
$this->hello = $hello;
$this->greetings = $greetings;
}
public function setBritish($hello = '', $greetings = '')
{
$this->hello = $hello;
$this->greetings = $greetings;
}
public function getHello()
{
return $this->hello;
}
public function getGreetings()
{
return $this->greetings;
}
}
$language = new Language;
// set language to English
$language->setEnglish("Hello", "Greetings");
echo '<p>' . $language->getHello() . '</p>';
您可以更好地重构此代码,我给出了一个起点!
答案 3 :(得分:0)
你非常接近。在使用变量之前,您需要在其中存储值。尝试修改你的类:
class Language {
private $hello;
private $greetings;
public function english() {
$this->hello = "Hello" . "<br>";
$this->greetings = "Greetings" . "<br>";
return $this;
}
public function british() {
$this->hello = "Ello there mate!" . "<br>";
$this->greetings = "Oi ya cheeky bugger" . "<br>";
return $this;
}
public function hello() {
return $this->hello . $this->greetings;
}
}
我稍微修改了你的函数以提供$hello
和$greetings
属性的一些封装,以使它感觉更多&#34; OOP&#34; ish if you would。此外,我还在return $this;
和english()
函数的末尾添加了british()
,以便您可以在调用时链接您的方法:
对于英语:
echo $this->english()->hello();
/* Output */
Hello
Greetings
对于英国人:
echo $this->british()->hello();
/* Output */
Ello there mate!
Oi ya cheeky bugger