2011-02-10 21 views
4

クラス内で定義された関数または変数を、クラス外からグローバル変数を使用せずに変更できますか?これはクラスが使用されている方法ですメインアプリケーションでPHP - クラス変数/関数をクラス外から変更する

class moo{ 
    function whatever(){ 
    $somestuff = "...."; 
    return $somestuff; // <- is it possible to change this from "include file #1" 
    } 
} 

、::

が、これは内部のファイル#2が含まれ、クラスである中、インスタンス属性として

include "file1.php"; 
include "file2.php"; // <- this is where the class above is defined 

$what = $moo::whatever() 
... 
+0

「ファイル1を含める」とはどういう意味ですか? – Gordon

+0

'$ somestuff'はローカル変数のようです。あなたは '$ what = moo :: whatever()'の後に '$ what'の値を変更できませんか? – BoltClock

+1

「関数を変更する」とはどういう意味ですか? – Dogbert

答えて

6

は、あなたがあなたの目標を達成するためのいくつかの可能性がありますGetterおよびSetterまたはStatic variables

class moo{ 

    // Declare class variable 
    public $somestuff = false; 

    // Declare static class variable, this will be the same for all class 
    // instances 
    public static $myStatic = false; 

    // Setter for class variable 
    function setSomething($s) 
    { 
     $this->somestuff = $s; 
     return true; 
    } 

    // Getter for class variable 
    function getSomething($s) 
    { 
     return $this->somestuff; 
    } 
} 

moo::$myStatic = "Bar"; 

$moo = new moo(); 
$moo->setSomething("Foo"); 
// This will echo "Foo"; 
echo $moo->getSomething(); 

// This will echo "Bar" 
echo moo::$myStatic; 

// So will this 
echo $moo::$myStatic; 
1

セットのそれをコンストラクタを呼び出すと、そのメソッドに属性の値が返されます。このようにして、参照を得ることができる場所であれば、異なるインスタンスの値を変更することができます。

3

について尋ねています。変数を設定して取得するには、getMethodsetMethodをクラスに書くことができます。

class moo{ 

    public $somestuff = 'abcdefg'; 

    function setSomestuff (value) { 
    $this->somestuff = value; 
    } 

    function getSomestuff() { 
    return $this->somestuff; 
    } 
} 
関連する問題