PHP从另一个类调用函数

时间:2014-03-05 22:28:57

标签: php class

目前在同一文件夹中调用其他PHP classes的函数时遇到问题。我已经实例化了这个类和所有东西,它仍然不适用于我。 从第一个类调用函数时得到的错误消息是:

method getHello() not found in class.

希望有人知道如何解决这个问题,相信我在某处做错了什么。 非常感谢您提前,下面是两个php文件的代码。

<?php
class one 
{

    private $hello;

    public function __construct()
    {
        $this->hello = '';
    }

    public function getHello()
    {
        return $this->hello;
    }

    public function setHello($newHello)
    {
        $this->hello = $newHello;
    }
}
?>

和第二类

<?php

class two 
{

    private $sixPack;

    public function __contruct()
    {
        $this->sixPack  = new one();
    }

    public function setSixPack($newSixPack)
    {
        $this->sixPack = $newSixPack;
    }

    public function getSixPack()
    {
        return $this->sixPack;
    }

    public function access_function_one_methods()
    {
        // this is causing the problem, cannot access getHello

        $sad = $this->sixPack->getHello();
    }
}
?>

2 个答案:

答案 0 :(得分:1)

这似乎有效,我不确定它是否是您想要的,但试一试:::

第二课的文件::         

            private $sixPack;

            public function __construct()
            {
                include_once('/Users/hakunamatata/Desktop/one.php');
                $this->sixPack  = new one();
                print("second construct \n");
            }

            public function setSixPack($newSixPack)
            {
                $this->sixPack = $newSixPack;
            }

            public function getSixPack()
            {
                return $this->sixPack;
            }

            public function access_function_one_methods()
            {
                // this is causing the problem, cannot access getHello
                print("function calling class one \n");
                $sad = $this->sixPack->getHello();
                echo $sad;
            }
          }
        $two = new two();
        echo $two->access_function_one_methods();
?>

第一课的文件::

<?php
    class one {

                    private $hello = "Je";
                    public function __construct()
                    {
                        print("first construct \n");
                        $this->hello = 'Hello';
                    }

                    public function getHello()
                    {
                        echo "we are here \n";
                        return $this->hello;
                    }

                    public function setHello($newHello)
                    {
                        $this->hello = $newHello;
                    }
                 }

?>

console output :::

first construct 
second construct 
function calling class one 
we are here 
Hello

答案 1 :(得分:0)

是构造函数中的一个spello?也许叫它__construct()? (想念s?)