2017-03-27 5 views
-1

私はそのメソッドに含まれるいくつかのプロパティ、つまりクラス全体ではないプロパティを定義したいと思います。しかし、オブジェクトのインスタンスからこれをやりたいそれは可能ですか?以下のコードは動作しません。php - メソッドのプロパティを定義することは可能ですか?

class foo{ 


var $x; 


function __construct(){ 


} 

function abc(){ 

echo $y; 

} 

} 


$new = new foo(); 

$new->abc->y = "bar"; 
+0

これはうまくいかない – Guesser

+0

[推奨される読書](http://www.php.net/manual/en/language.oop5.basic.php) –

答えて

1
/* 
* I have trimmed this down because of redundant entries, and only 
* modified what you had written 
*/ 

class foo 
{ 
    /* 
    * I have made this public so you can access this globally 
    */ 

    public function abc($y) 
    { 
     echo $y; 
    } 
} 

$new = new foo(); 

/* 
* Instead of passing a value directly to the variable inside the 
* method, I made the method accept properties that will modify 
* the variable. You cannot do this if you have not made the method 
* 'public'. 
*/ 

$new->abc("bar"); // the method contains an echo statement, so it will echo "bar" 

?> 

お役に立てば幸いです。

関連する問題