在 PHP 中将对象作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9332596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:35:12 来源:igfitidea点击:
Pass an object as parameter in PHP
提问by Hoan Dang
In Java, I can pass an object straight in parameter
在 Java 中,我可以直接在参数中传递一个对象
public int foo (Bar bar)
{
... call the methods from Bar class
}
So how can I do same thing with PHP. Thanks This is my code:
那么我如何用 PHP 做同样的事情。谢谢 这是我的代码:
class Photo
{
private $id, $name, $description;
public function Photo($id, $name, $description)
{
$this->id = $id;
$this->name = $name;
$this->description = $description;
}
}
class Photos
{
private $id = 0;
private $photos = array();
private function add(Photo $photo)
{
array_push($this->photos, $photo);
}
public function addPhoto($name, $description)
{
add(new Photo(++$this->id, $name, $description));
}
}
$photos = new Photos();
$photos->addPhoto('a', 'fsdfasd');
var_dump($photos); // blank
If I change the function add
如果我改变功能添加
function add($name, $description)
{
array_push($this->photos, new Photo(++$this->id, $name, $description));
}
It works pefectly. So What is wrong ?
它完美地工作。那么有什么问题呢?