包含文件中的新类


new class in included files

我有一些类,这些类包含在index.php文件中,如:

<?php
 include("./includes/user.class.php");
 include("./includes/anotherclass.class.php");
?>

那么我有:

  $layout = new layout();
  $layout->sampleMethod;

那么在body中我有:

include("pages/samplePage.php");

samplePage.php

我必须再次创建new layout()来使用类函数,是否有一种方法可以在不创建另一个对象的情况下使用$layout->method在包含的文件?

更多代码:

布局类:

public function mkLayout()
  {
    include("pages/page.php");
  }
public function getPageUrl()
  {
    echo "PAGE URL";
  }

index.php:

<?php
  require_once("includes/layout.class.php");
  $layout = new layout();
  $layout->mkLayout();
?>

一些samplpage .php

  <?php
    $layout->getPageUrl();
   ?>

samplpage .php返回

Fatal error: Call to a member function getPageUrl() on a non-object in

如果您在包含的页面中使用$layout,它应该正常工作,当然假设您在包含samplePage.php之前声明了$layout = new layout();

如果它不适合你,尝试var_dump()在你的包含页面,看看你得到什么。虽然它应该像你要求的那样工作。

<标题>编辑!

在深入研究之后,我发现无论文件包含在哪里,它都会继承使用它的函数/方法的作用域,所以使用

global $layout;

在您尝试使用方法之前,它应该可以正常工作。

:

当包含一个文件时,它所包含的代码将继承发生包含的那一行的变量范围。从那时起,在调用文件的那一行可用的任何变量都将在被调用的文件中可用。但是,在包含的文件中定义的所有函数和类都具有全局作用域。

的有用链接:

  • 变量作用域- PHP手册

不,除非您想包含包含先前布局类实例化的文件。

也许在这个例子中您并没有真正努力实现面向对象。

如果你的代码看起来是这样的,那么

<?php
    include("./includes/user.class.php");
    include("./includes/anotherclass.class.php");
    $layout = new layout();
    $layout->sampleMethod;
    include("pages/samplePage.php");
?>  

$layout应该已经在你的pages/samplePage.php中声明了。尝试在pages/samplePage.php中执行var_dump($layout),您将看到它已经定义。


为什么不在你的类里面有一个布局成员呢?