0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP5.3 で、Datetime型のPass by value ができない

Last updated at Posted at 2019-07-02

題名通りです。早速コードと出力結果を載せます。

	private function pass_date_by_val($date){
	    $date->modify('-3 month');
	}
	
	private function pass_str_by_val($str){
	    $str = "Yahoo";
	}

	$new_date = new \DateTime();
	echo $new_date->format('Y-m-d H:i:s')."\n";
	$this->pass_date_by_val($new_date);
	echo $new_date->format('Y-m-d H:i:s')."\n";
	    
	$new_str = "Google";
	echo $new_str."\n";
	$this->pass_str_by_val($new_str);
	echo $new_str."\n";

出力:

2019-07-02 10:35:08
2019-04-02 10:35:08
Google
Google

↑の通り、文字列は値で渡しているのに対し、Datetimeは参照で渡された!

同じ悩みを抱え方もいる。ボブジェクトは基本Javaみたいに参照で渡している?

#回避策
そこにハマってしょうがないので、clone で乗り越えよう!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?