我一直在用JAVA编程并用PHP编写过程程序,但现在我尝试用PHP编写一些OOP基础程序,我遇到了问题。
我有两个文件Zoo.php
和Dog.php
,每个文件都包含一个类。
Dog.php:
<?php
class Dog {
private $name;
private $color;
public function __construct($name,$color) {
$this->name = $name;
$this->color = $color;
}
public function getName(){
return $this->name;
}
public function getColor(){
return $this->color;
}
}
Zoo.php :
<?php
class Zoo {
private $name;
private $dogs;
public function __construct($name) {
$this->name = $name;
$dogs = array();
}
public function addDog($dogName,$dogColor){
$dog = new Dog($dogName,$dogColor);
array_push($this->dogs,$dog);
}
public function getAllDogs(){
var_dump($dogs);
}
}
echo "start";
$z = new Zoo("test_zoo");
$z->addDog("blackie","black");
$z->getAllDogs();
上面的代码输出:
Fatal error: Class 'Dog' not found in C:\wamp\www\Zoo.php on line 13
我想知道上面的代码有什么问题,以及如何在PHP中创建另一个对象中的对象实例。提前谢谢。
答案 0 :(得分:1)
答案 1 :(得分:0)
不是关于OOP。只是你忘了把Dog文件包含在Zoo类中使用它:
<?php
include 'Dog.php'; // or whatever path
class Zoo { ...
其他一切都应该没问题,似乎很好地利用了PHP OOP btw。 :)
答案 2 :(得分:0)
您尚未在Dog.php
中加入Zoo.php
。因此,您无法创建新实例。
在Zoo类上面添加:
include("Dog.php");
class Zoo {
答案 3 :(得分:0)
所有你需要返回功能。 这里有三个错误,你会在我的代码中看到所有错误。构造函数没有返回,表现得像void,所以我们需要一个返回dog规范的方法。如果你想在单独的文件中使用这些类,那么你必须使用“include”或“require”或“require_once”等的php方法(看看这个方法的区别)
<?php
class Dog {
private $name;
private $color;
public function __construct($name,$color) {
$this->name = $name;
$this->color = $color;
}
public function getName(){
return $this->name;
}
public function getColor(){
return $this->color;
}
public function getDogs(){
return array("name"=>$this->name,"color"=>$this->color);
}
}
class Zoo extends Dog{
private $name;
private $dogs=array();
public function __construct($name) {
$this->name = $name;
$dogs = array();
}
public function addDog($dogName,$dogColor){
$dog = new Dog($dogName,$dogColor);
array_push($this->dogs,$dog->getDogs());
}
public function getAllDogs(){
var_dump($this->dogs);
}
}
echo "start";
$z = new Zoo("test_zoo");
$z->addDog("blackie","black");
$z->getAllDogs();
?>