メソッドチェーン2

<?php

class Sum {
	private $sum = 0;
	public static function _(){
		return new self;
	}

	public function add($a){
		$this->sum += $a;
		return $this;
	}
	public function out(&$result){
		$result = $this->sum;
		return $this;
	}
}

Sum::_()->add(1)
		->add(3)
		->out($result1)
		->add(5)
		->add(8)
		->out($result2);
echo "$result1\t$result2";
?>

サンプル2
オークションで例えてみましょう。

<?php

class Auction {
	private $sum=50000;
	public static function _(){
		return new self;
	}

	public function sell($sales){
		$this->sum += $sales;
		return $this;
	}

	public function buy($stock){
		$this->sum -= $stock;
		return $this;
	}

	public function amount(&$result){
		$result = $this->sum;
		return $this;
	}
}

Auction::_()->sell(5000)
			->buy(3000)
			->sell(2000)
			->amount($result1)
			->sell(5000)
			->sell(2000)
			->sell(1000)
			->amount($result2);

echo "$result1\t$result2";
?>

return new self();

<?php

class A {
	public static function get_self(){
		return new self();
	}

	public static function get_static(){
		return new static();
	}
}

class B extends A {}

echo get_class(B::get_self());
echo get_class(B::get_static());
echo get_class(A::get_static());

?>

スコープ定義演算子(::)

<?php

class Box1
{
	public static function hoge(){
		Box2::hoge();
	}
}

class Box2
{
	public static function hoge(){
		echo 'Gold' . PHP_EOL;
	}
}

Box1::hoge();
?>

サンプル2

<?php

class Tse2
{
	public static function reg(){
		self::cap();
	}

	public static function cap(){
		echo "時価総額20億円以上". PHP_EOL;
	}
}

class Tse1 extends Tse2
{
	public static function cap(){
		echo "時価総額250億円以上". PHP_EOL;
	}
}

Tse2::reg();
Tse1::reg();

?>
<?php

class Tse2
{

	public static function cap(){
		echo "時価総額20億円以上". PHP_EOL;
	}
}

class Tse1 extends Tse2
{
	public static function reg(){
		parent::cap();
	}

	public static function cap(){
		echo "時価総額250億円以上". PHP_EOL;
	}
}

Tse1::reg();

?>

メソッドチェーン2

<?php

$abc = '変数abc';
echo $abc, PHP_EOL;
echo ${'abc'}, PHP_EOL;
$name = 'abc';
echo ${$name}, PHP_EOL;
echo $$name, PHP_EOL;

function abc(){
	echo '関数abcが実行されました', PHP_EOL;
}
abc();
$name = 'abc';
$name();
?>
<?php

class Chain {
	public static function _(){
		return new self;
	}

	public function p($name){
		echo $name;
		return $this;
	}
}

Chain::_()->p('hoge')->p('fuga');

メソッドチェーン

メソッドチェーンとは、メソッドをアロー演算子で複数つなぎ、複数のメソッドを一度に行うことです。

サンプルを見てみましょう。

<?php

class Product
{
	private $price = 100;

	public function getPrice()
	{
		return $this->price;
	}
}

class Cart
{
	private $products = array();

	public function add($product)
	{
		$this->products[] = $product;
	}

	public function get($index)
	{
		return $this->products[$index];
	}
}

$cart = new Cart();
$product = new Product();
$cart->add($product);

$prd = $cart->get(0);
$price = $prd->getPrice();

$price = $cart->get(0)->getPrice();

?>
<?php

class Date
{
	private $_timestamp;

	public function __construct()
	{
		$this->_timestamp = time();
	}

	public function addDay($days)
	{
		if (true == preg_match('/^[0-9]+$/', $days)){
			$str = sprintf('+%s day', $days);
			$this->_timstamp = strtotime($str, $this->_timestamp);
		}
	}

	public function format($format)
	{
		return date($format, $this->_timestamp);
	}
}

$date = new Date();
$date->addDay(3);
$fmt = $date->format('Y/m/d H:i');
var_dump($fmt);

?>
<?php

class Chain {
	protected $price;
	protected $quantity;
	protected $option;

	public function setPrice($price){
		$this->price = $price;
		return $this;
	}	

	public function setQuantity($quantity){
		$this->quantity = $quantity;
		return $this;
	}

	public function setOption($option){
		$this->optioin = $option;
		return $this;
	}

	public function get(){
		$amount = $this->price * $this->quantity;
		foreach ($this->option as $key => $val){
			if ($key == 'tax') $amount -= ceil($amount * $val);
			elseif($key == 'discount') $amount -= $val;
		}

		return $amount;
	}
}

$chain = new Chain();
$chain
 ->setPrice(100)
 ->setQuantity(5)
 ->setOption(array(
 	'tax' => '0.05',
 	'discount' => '150'
 	));
 $total_amount = $chain->get();
 echo $total_amount;

?>

array()

配列は複数の値をまとめたもので、データをキー/値のペアにしています。配列には順序があり、要素が追加された順に並んでいます。

<?php

$sushi = array('大トロ', '中とろ', '赤身', 'ネギトロ');

echo $sushi&#91;0&#93;."<br>\n";
echo $sushi[1]."<br>\n";
echo $sushi[2]."<br>\n";
echo $sushi[3]."<br><br>\n";

$chinese = array('peanuts' => '油揚げピーナッツ', 'mushroom' => 'アワビ', 'chicken'=> '鶏肉の激辛ソースがけ');

echo $chinese['peanuts']."<br>\n";
echo $chinese['mushroom']."<br>\n";
echo $chinese['chicken']."<br><br>\n";

$pasta[] = 'クリームフェットチーネ';
$pasta[] = 'ずわい蟹と魚介たっぷりブイヤベース';
$pasta[] = '牡蠣のクリームスープパスタ';

echo $pasta[0]."<br>\n";
echo $pasta[1]."<br>\n";
echo $pasta[2]."<br>\n";

?>

strtotime()

英文形式の日時をUNIXタイムスタンプに変換する
指定された文字列が解釈不能な場合や、タイムスタンプの最大値を超えた場合は-1を返す。

サンプル

<?php

$now = strtotime("now");
$tomorrow = strtotime("tomorrow");

echo '現在時刻:'.date('Y年m月d日 H時i分s秒', $now)."<br>\n";
echo '明日:'.date('Y年m月d日', $tomorrow)."<br>\n";
?>

分かりにくいので、請求書催促の例でみてみましょう。

<?php

$deadline = strtotime("+2 week");

echo "請求書の支払期日を過ぎてもご入金を確認できませんでした。<br>";
echo 'つきましては、二週間後の'.date('Y年m月d日', $deadline)."までにご入金をお願いいたします。";
?>

date関数

-date関数は引数を1つ持てる
-引数1つの時は、現在時刻を指定したフォーマットで出力
-引数2つの時は第二引数のタイムスタンプを指定したフォーマット
-戻り値はstring

サンプル

<?php

date_default_timezone_set('Asia/Tokyo');

echo date("Y/m/d H:i:s") ."<br>";
echo date("Y/m/01") ."<br>";
echo date("Y/m/t")  ."<br>";

$w = date("w");
$week_name = array("日","月","火","水","木","金","土");

echo date("Y/m/d") . "($week_name[$w])\n";
?>

東京、ロンドン、ニューヨークを表示してみましょう。

<?php

date_default_timezone_set('Asia/Tokyo');

$w = date("w");
$week_name = array("日","月","火","水","木","金","土");

echo "東京<br>";
echo date("Y/m/d H:i:s") . "($week_name[$w])<br>";


date_default_timezone_set('Europe/London');
$week_name = array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");

echo "London<br>";
echo date("Y/m/d H:i:s") . "($week_name[$w])<br>";


date_default_timezone_set('America/New_York');

echo "New York<br>";
echo date("Y/m/d H:i:s") . "($week_name[$w])<br>";
?>

住宅ローンの返済月のサンプルです。

<?php

$rate = 0.0135;
$loan = 30000000;
$payment = 85000;
$i = 0;

while($loan > 0){
	$loan = $loan - ($payment - ($loan*$rate / 12));
	$i = $i + 1;
}
$hensai = $i + 1;

date_default_timezone_set('Asia/Tokyo');
echo date("Y/m", strtotime(" + $hensai month"));

?>

Analytics API3

<?php
	
	require_once 'vendor/autoload.php';

	$client_id = 'xxxx';

	$view_id = 'xxxx';

	$private_key = @file_get_contents('xxxx');

	$from = date('2017-12-01', strtotime('-1 day'));
	$to = date('2018-01-31');

	$dimensions = 'ga:pageTitle, ga:pagePath, ga:date';
	$metrics = 'ga:pageviews';

	$option = array(
		'dimensions' => $dimensions,
		'max-results' => 10,
		'sort' => '-ga:pageviews',
		'start-index' => 11,
	);

	if(isset($_SESSION['service_token']))
	{
		$client->setAccessToken($_SESSION['service_token']);
	}

	$scopes = array('https://www.googleapis.com/auth/analytics.readonly');

	$credentials = new Google_Auth_AssertionCredentials($client_id, $scopes, $private_key);

	$client = new Google_Client();
	$client->setAssertionCredentials($credentials);

	if($client->getAuth()->isAccessTokenExpired())
	{
		$client->getAuth()->refreshTokenWithAssertion($credentials);
	}

	$_SESSION['service_token'] = $client->getAccessToken();

	$analytics = new Google_Service_Analytics($client);

	$obj = $analytics->data_ga->get('ga:'. $view_id, $from, $to, $metrics, $option);

	$json = json_encode($obj);

	$html .= '<h2>実行結果</h2>';
	$html .= '<p><b>' .date('Y/m/d', strtotime($from)). '</b>のページビューのデイリーランキングを取得しました。<mark>値はサンプル用のダミーです。</mark></p>';

	if(!isset($obj->rows))
	{
		$html .= '<p><mark>データを取得できませんでした。</mark></p>';
	}
	else
	{
		$html .= '<ol>';

		for($i=0, $l=count($obj->rows); $l > $i ; $i++)
		{
				$item = $obj->rows[$i];
				$html .= '<li><a href="' . $item&#91;l&#93; .'"target="_blank">' .$item[0]. '<a>(' . number_format($item[3]). 'PV)</li>';		
		}
		$html .= '</ol>';
	}

	$html .= '<h2>取得したデータ(JSON)</h2>';
	$html .= '<textarea row="12">' . $json . '</textarea>';

?>

<?php
		echo $html;
?>

file_get_contents()

指定したファイルの内容を全て取得する関数です。

<?php
$contents = file_get_contents('test.txt');
echo $contents;
?>