Ale*_*lex 6 php oop class function
我试图学习OOP而且我已经完成了这门课程
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在another_class课堂上的某个地方称之为
$bla = new boo($bla, $foo);
echo $bla->do_stuff();
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在do_stuff函数中访问$ bla,$ foo
Log*_*ley 12
<?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;
Run Code Online (Sandbox Code Playgroud)
请不要在PHP 5中通过引用传递,没有必要,我读过它实际上更慢.
我在课堂上声明了变量,尽管你不必那样做.
irc*_*ell 10
好的,首先,使用较新的样式构造函数__construct而不是类名的方法.
class boo{
public function __construct($another_class, $some_normal_variable){
Run Code Online (Sandbox Code Playgroud)
其次,要回答您的具体问题,您需要使用成员变量/属性:
class boo {
protected $another_class = null;
protected $some_normal_variable = null;
public function __construct($another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $some_normal_variable;
}
function do_stuff(){
return $this->another_class->get($this->some_normal_variable);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,请注意,对于成员变量,在类的内部,我们通过为它们添加前缀来引用它们$this->.这是因为属性绑定到这个类的实例.这就是你要找的......