-1

可能重复:
我如何在 php 类中包含 php 文件

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

<?php

include("strings.php");

class example {

strings.php 的格式如下

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

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

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

4

3 回答 3

1

Depends:

Do the entire (or most of the) object need the strings to work, or just a method or two?

  • If yes, you should pass it in the constructor of the object:

    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);
    
  • If not, you should pass it in to the relevant method which needs it.

    class Example {
        private $texts;
    
        public function method($texts) {
            //Do stuff with $texts
        }
    }
    
    $example = new Example;
    $example->method($txt);
    
于 2012-10-07T14:23:20.740 回答
0

An included file that just defines variables generally is a sign for bad design and definitely not OOP. But if you have to work with that, include the file from within the class and let it return the array:

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

        $this->txt = include($include);
    }
    public function someMethod()
    {
        return $this->txt['somestring'];
    }
}
于 2012-10-07T14:22:11.373 回答
-2

Unless strings.php contains any more wrapping code $txt is a global variable. Php does not allow access to normal global variables from within functions and methods unless explicitly declared.

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

You call it by first declaring it in the function

class MyClass{

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

This is a citation from 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
于 2012-10-07T14:23:01.100 回答