-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

依存:

オブジェクト全体 (または大部分) が機能するために文字列が必要ですか、それとも 1 つまたは 2 つのメソッドだけですか?

  • はいの場合は、オブジェクトのコンストラクターに渡す必要があります。

    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);
    
于 2012-10-07T14:23:20.740 に答える
0

変数を定義するだけのインクルード ファイルは、通常、設計が悪いことを示しており、間違いなく OOP ではありません。ただし、それを処理する必要がある場合は、クラス内からファイルを含めて、配列を返すようにします。

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

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
于 2012-10-07T14:23:01.100 に答える