PHP-将变量传递给类 [英] PHP - passing variables to classes
本文介绍了PHP-将变量传递给类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图学习OOP,并且已经完成了这堂课
I trying to learn OOP and I've made this class
class boo{
function boo(&another_class, $some_normal_variable){
$some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $another_class->get($some_normal_variable);
}
}
我在 other_class
类之内的某个地方称它为
and I call this somewhere inside the another_class
class like
$bla = new boo($bla, $foo);
echo $bla->do_stuff();
但是我不知道如何在do_stuff函数中访问$ bla,$ foo
But I don't know how to access $bla, $foo inside the do_stuff function
推荐答案
<?php
class Boo
{
private $bar;
public function setBar( $value )
{
$this->bar = $value;
}
public function getValue()
{
return $this->bar;
}
}
$x = new Boo();
$x->setBar( 15 );
print 'Value of bar: ' . $x->getValue() . PHP_EOL;
请不要在PHP 5中通过引用传递它,没有必要,而且我读到它实际上要慢一些.
Please don't pass by reference in PHP 5, there is no need for it and I've read it's actually slower.
我在类中声明了变量,尽管您不必这样做.
I declared the variable in the class, though you don't have to do that.
这篇关于PHP-将变量传递给类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文