Php 包含文件中的新类

Php 包含文件中的新类,php,oop,include,Php,Oop,Include,我有一些类,这些类包含在index.php文件中,比如: <?php include("./includes/user.class.php"); include("./includes/anotherclass.class.php"); ?> 那么在身体里我有: include("pages/samplePage.php"); 然后在那samplePage.php 我必须再次创建newlayout()才能使用类函数,有没有办法在包含的文件中使用$layout->method,

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

<?php
 include("./includes/user.class.php");
 include("./includes/anotherclass.class.php");
?>
那么在身体里我有:

include("pages/samplePage.php");
然后在那
samplePage.php

我必须再次创建
newlayout()
才能使用类函数,有没有办法在包含的文件中使用
$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();
?>

如果您的代码看起来是这样的,那么请删除您发布的内容:

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

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

    include("pages/samplePage.php");
?>  

$layout
应该已经在
页面/samplePage.php
中声明。尝试在
pages/samplePage.php
中执行
var\u dump($layout)
,您将看到它已经定义好了



为什么不在您的类中设置一个布局成员呢?

如果您在包含的页面中使用
$layout
,它应该可以正常工作,当然前提是您声明了
$layout=newlayout()
在包含
samplePage.php
之前

如果它对您不起作用,请尝试
var\u dump()。尽管它应该按照你的要求工作

编辑 经过一点挖掘,我发现无论文件包含在哪里,它都继承了使用它的函数/方法的范围,所以请使用

global $layout;
在您尝试使用方法之前,它应该工作良好

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

有用链接:


否,除非您希望包含包含layout类先前实例化的文件。

在本例中,您可能并没有真正努力实现面向对象。考虑只使用没有类的普通函数。

如果你从函数的内部包含<代码> SAMPLIPURIP.PHP<代码>,我想可以使用<代码> $<这个< /代码>。但是我不确定,你的包含结构不是很好,你想在所有的脚本中都包含类或函数库,除了一个执行脚本,差不多。这意味着一般情况下,您应该使用
require\u一次
library includes,而不仅仅是
include
。哦,它已经是require\u一次了),但是感谢您的建议
samplePage.php
在哪里被包含?这是我在测试时得到的结果:它返回空值。我只想在包含的页面中使用$layout->方法,而不创建新对象。结构:index.php包括类并创建对象($layout=new layout();),然后layout类包括页面(page/samplepage.php),然后我想在samplepage.php文件中使用$layout对象方法,但我不想为每个页面创建新对象发布更多的代码,应该根据您提供的定义它。是否尝试在另一个类中访问$layout?从layout classvar_dump()调用include返回空值。工作原理:index.php包含类并创建对象($layout=new layout();),然后layout类包含页面(page/samplepage.php),然后我想在samplepage.php文件中使用$layout对象方法,但我不想为每个页面创建新对象它应该按照您的描述工作,我会自己做一些测试看看。我测试并确认了你的问题,尽管我被难住了。真棒的问题。让我们看看是否没有人能回答,我会贴一张bounty@John找到了。自由使用
global
的变量范围不是最好的
Fatal error: Call to a member function getPageUrl() on a non-object in
<?php
    include("./includes/user.class.php");
    include("./includes/anotherclass.class.php");

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

    include("pages/samplePage.php");
?>  
global $layout;