在类别中调用函数,然后调用默认索引()?

时间:2015-01-03 11:44:37

标签: php function class oop

我有一个类,

class test
{

  public function index()
  {

  }

  public function home()
  {

  }

}

但当我打电话给我的班级时,

$test = new test();

它将执行默认函数index(),我的问题是如何调用函数home()并忽略函数index()?

我尝试在创建类的对象之后调用该函数,如$ test-> home()但它仍然首先调用index()然后调用home()。

一点帮助或指示将不胜感激,

谢谢, 阿里

2 个答案:

答案 0 :(得分:2)

是的,你可以通过这样添加魔术方法__construct()来做到这一点:

<?php

    class index {

        public function __construct() {
            echo "1";
        }

        public function index() {
            echo "2";
        }

        public function home() {
            echo "3";
        }

    }

    $obj = new index();
    $obj->index();
    $obj->home();

?>

输出:

123

如您所见,您可以看到每个方法都被调用

答案 1 :(得分:0)

实例化类时,不会调用这些函数。实例化时调用的函数是__construct()

因此,如果您想在实例化类时调用home(),请在您的类中使用以下函数。

function __construct() {
    $this->home();
}

实例化该课程会调用__construct(),然后调用home()