在课堂上包括字符串

时间:2012-10-07 14:15:23

标签: php

  

可能重复:
  how can i include php file in php class

我有一个像这样开始的PHP文件:

<?php

include("strings.php");

class example {

strings.php格式如下

$txt['something'] = "something";
$txt['something_else'] = "something else";

我的问题是,如何在$txt['something']课程中调用方法中的example? 我知道$this->txt['something']不起作用

这可能是基本的东西,但我刚开始学习PHP

3 个答案:

答案 0 :(得分:1)

取决于:

整个(或大部分)对象是否需要字符串才能工作,或只是一个或两个方法?

  • 如果是,您应该在对象的构造函数中传递它:

    class Example {
        private $texts;
    
        public function __construct($texts) {
            $this->texts = $texts; //Now the array is available for all of the methods in the object, via $this->texts
        }
    }
    
    $example = new Example($txt);
    
  • 如果没有,您应该将传递给需要它的相关方法

    class Example {
        private $texts;
    
        public function method($texts) {
            //Do stuff with $texts
        }
    }
    
    $example = new Example;
    $example->method($txt);
    

答案 1 :(得分:0)

只是定义变量的包含文件通常是设计错误的标志,绝对不是OOP。但是如果你必须使用它,请在类中包含该文件并让它返回数组:

class Example
{
    protected $txt;
    public function __construct($include = 'strings.php')
    {

        $this->txt = include($include);
    }
    public function someMethod()
    {
        return $this->txt['somestring'];
    }
}

答案 2 :(得分:-2)

除非strings.php包含更多包装代码,否则$ txt是一个全局变量。 除非明确声明,否则Php不允许从函数和方法中访问常规全局变量。

http://php.net/manual/en/language.variables.scope.php

首先在函数

中声明它来调用它
class MyClass{

public function MyMethod() {
{
    global $txt;
    echo $txt['fddf'];

这是来自php.net的引文

<?php
$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable