たぼさんの部屋

いちょぼとのんびり

基本的なPHP構文

構文例

<?php
/**
 * @author kamogashira
 * class test
 * コンストラクタ:function __construct($args){}
 * コンストラクタのアクセス制限:publicのみ(private,protectedは使用できない)
 * コンストラクタは複数作成することはできない(このばあいは可変長引数を使う)
 * 可変長引数リスト:func_num_args(),func_get_arg(),func_get_args()
 *
 * クラス内メンバ変数へのアクセス:$this->変数
 * 継承:extends
 * 親クラスのコンストラクタ呼び出し:parent::__construct($args); 明示的に呼び出し必須
 *
 * staticプロパティ:static $args
 * クラス内での呼び出し:self::$args
 * クラス外からの呼び出し:クラス名::$args publicなとき
 *
 */
header("Content-type: charset=UTF-8");
class Rectangle{
   public static $counter = 0;                                 //static変数 記述
   private  $x=0,$y=0;

   public function __construct($x,$y){                         //コンストラクタ
      self::$counter ++;                                       //static変数へのアクセス
      $this->x = $x;                                        //インスタンス変数へのアクセス
      $this->y = $y;
   }
   public function getArea(){
      return $this->x * $this->y;                        //インスタンス変数へのアクセス
   }
   public function getCounter(){
      return self::$counter;                                   //static変数
   }
}

class Line{
   private $x,$y;
   public function __construct(){                              //可変長引数を使う
      if(func_num_args()===0){
         $this->x = 0;
         $this->y = 0;
      }
      else{
         $this->x = func_get_arg(0);
         $this->y = func_get_arg(1);
      }
   }
   public function getPoints(){
      return array("x"=>$this->x , "y"=>$this->y);
   }
}

class NamedLine extends Line{                                   //extends
   private $name = "default";
   public function __construct(){
      parent::__construct();
      print func_num_args();
   }
   public function getName(){
      return $this->name;
   }
}

$rect = new Rectangle(10, 20);
print $rect->getArea() . "\n";
echo $rect->getCounter();
echo Rectangle::$counter;

//継承
$namedline = new NamedLine();
echo $namedline->getName();
echo $namedline->getPoints();
$array =$namedline->getPoints();
echo array_key_exists("x" , $array); //配列にキーがあるかどうか判定
$x = $array["x"]; //配列のキーを直接指定
echo $x;
?>