プログラミング系のネタをまとめていきます。

演算子

比較演算子 ==, ===

==型変換後の値を比較し、等しい場合に true
===値が等しく、型も等しい場合に true

●ソースコード

var_dump(1 == true); echo '<br>';	// trueが1にキャストされて true
var_dump(1 === true); echo '<br>';	// int と boolで型が違うので false

●出力結果

bool(true) 
bool(false) 

変数

スコープ

グローバルスコープ、ローカルスコープ

$a = 1;		// グローバルスコープ

function func()
{
	echo $a;	// ローカルスコープの変数を参照
}

func();

グローバル変数を参照する

$a = 1;
$b = 2;

function Sum()
{
	global $a, $b;	// グローバル変数を参照する
	$b = $a + $b;
}

Sum();
echo $b;	// 3が出力される

$a = 1;
$b = 2;

function Sum()
{
	$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];	// グローバル変数にアクセスする
}

Sum();
echo $b;	// 3が出力される

include と変数スコープ

$a = 1;

include 'b.inc';	// $a は b.inc の中でも有効

静的変数


function test()
{
	static $a = 0;	// "0"初期化は最初の1回のみ
	echo $a;
	$a++;
}

静的な宣言はコンパイル時に解決されるので、静的変数は式の結果を代入できない。

static $int = 0;          // 正しい
static $int = 1+2;        // 間違い
static $int = sqrt(121);  // 間違い

ダブルクォーテーション、シングルクォーテーションの違い

ダブルクォーテーション文字列内の変数が評価される
シングルクォーテーション文字列内の変数は評価されない
エスケープシーケンスも処理されない
処理が高速


$str = 'これくしょん';

echo "艦隊$str";	// -> 「艦隊これくしょん」と出力される

echo '艦隊$str\n';	// -> 「艦隊$str\n」と出力される

クラス定義


●ソースコード

class TestClass
{
	// static変数
	public static $staticParam;

	private $param;

	// コンストラクタ
	public function __construct()
	{
		echo '> '.get_class($this).'.__construct()<br>';
	}

	public function setParam($p)
	{
		$this->param = $p;
	}
	
	public function output()
	{
		echo 'param = '.$this->param.'<br>';
	}
	
	// static関数
	public static function outputStatic()
	{
		echo 'staticParam = '.self::$staticParam.'<br>';
	}
}

class TestClass2 extends TestClass	// クラス継承
{
	public static function outputStatic()
	{
		echo 'parent staticParam = '.parent::$staticParam.'<br>';	// 親クラスのstatic変数を取得
	}
}


$obj1 = new TestClass();
$obj1->setParam('TestParam1');
$obj1->output();

TestClass::$staticParam = 'StaticParam1';
TestClass::outputStatic();

echo '<br>';

$obj2 = new TestClass2();
$obj2->setParam('TestParam2');
$obj2->output();

TestClass2::outputStatic();


●出力結果


> TestClass.__construct()
param = TestParam1
staticParam = StaticParam1

> TestClass2.__construct()
param = TestParam2
parent staticParam = StaticParam1
タグ

Menu

メインコンテンツ

プログラミング

機器

Macツール

各種情報

Wiki内検索

おまかせリンク

Androidアプリ

AdSense

技術書


管理人/副管理人のみ編集できます