Phi*_*lla 5 php parameters class byref
我怎样才能将一个类作为参数传递给我的函数
到目前为止我已经尝试过了
Run Code Online (Sandbox Code Playgroud)$sc = new SampleClass(); SampleFunction($sc); function SampleFunction(&$refClass) { echo $refClass->getValue(); }
这是我正在做的简化示例..我实际上必须在此示例函数中执行复杂的过程.我没有从示例函数中得到任何响应.我究竟做错了什么?谢谢
UPDATE
char.php
class Charss {
var $name=0;
var $hp=500;
var $spd=10;
var $rtime=10;
var $dmg=10;
function __construct( $name, $hp, $spd, $rtime , $dmg) {
$this->name = $name;
$this->hp = $hp;
$this->spd = $spd;
$this->rtime = $rtime;
$this->dmg = $dmg;
}
function get_name() {
return $this->name;
}
function set_name($new_name) {
$this->name = $new_name;
}
function get_hp() {
return $this->hp;
}
function set_hp($new_hp) {
$this->hp = $new_hp;
}
function get_spd() {
return $this->spd;
}
function set_spd($new_spd) {
$this->spd = $new_spd;
}
function get_rtime() {
return $this->rtime;
}
function set_rtime($new_rtime) {
$this->rtime = $new_rtime;
}
function get_dmg() {
return $this->get_dmg;
}
function set_dmg($new_dmg) {
$this->dmg = $new_dmg;
}
}
Run Code Online (Sandbox Code Playgroud)
myclass.php
require("char.php");
class Person {
function try_process()
{
$chr1 = new Charss("Player1",500,3,0,50);
$chr2 = new Charss("Player2",500,6,0,70);
while ($chr1->get_hp() > 0 && $chr2->get_hp() > 0)
{
$sth = min($chr1->get_rtime(), $chr2->get_rtime());
if ($chr1->get_rtime() == 0 && $chr2->get_rtime() > 0)
{
exit;
Fight($chr1,$chr2);
$chr1->set_rtime($chr1->get_spd());
}
elseif ($chr2->get_rtime() == 0 && $chr1->get_rtime() > 0)
{
Fight($chr2,$chr1);
$chr2->set_rtime($chr2->get_spd());
}
else
{
Fight($chr1,$chr2); #having trouble with this
$chr1->set_rtime($chr1->get_spd());
}
$chr1->set_rtime($chr1->get_rtime() - $sth);
$chr2->set_rtime($chr2->get_rtime() - $sth);
}
}
function Fight($atk,$def)
{
$def->set_hp($def->get_hp() - $atk->get_dmg());
echo $atk->get_name() . " attacked " . $def->get_name() . " for " . $atk->get_dmg() . " damage";
}
Run Code Online (Sandbox Code Playgroud)
}
所以我在按钮点击时调用函数try_process
你实际上在那里做的是传递一个对象,而不是一个类。
$sc = new SampleClass();
Run Code Online (Sandbox Code Playgroud)
创建 SampleClass 的实例,也称为对象。
我认为在其他地方抛出了一些错误,因为您所拥有的是正确的。我测试了以下代码并得到了预期的输出:
class SampleClass
{
public function getValue()
{
return 4;
}
}
$sc = new SampleClass();
SampleFunction($sc);
function SampleFunction(&$refClass)
{
echo $refClass->getValue();
}
Run Code Online (Sandbox Code Playgroud)
输出:4
如果您提供实际代码的更多详细信息,我们也许能够确定问题。
| 归档时间: |
|
| 查看次数: |
16811 次 |
| 最近记录: |