douwei3172 2014-08-14 13:31
浏览 24
已采纳

PHP从另一个对象调用对象

I've been programming mainly with JAVA and have written procedural programs in PHP, but now I'm try to write some OOP bases programs in PHP and I'm facing a problem. I've got two files , Zoo.php and Dog.php , each contains a class.

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;
     }
}

And 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();

The code above outputs :

Fatal error: Class 'Dog' not found in C:\wamp\www\Zoo.php on line 13

I'd like to know what's wrong with the code above and how creating an object instance within another object should be done in PHP. Thanks in advance.

  • 写回答

4条回答 默认 最新

  • duanlvxing7707 2014-08-14 13:34
    关注

    I gues you are not including Dog class.

    <?php
    include "Dog.php";
    
    class Zoo {
    /* ... */
    }
    

    Or you can use autoloading to auto include any class by default.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害