facebook twitter hatena line email

Php/php5クラスメモ

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

__callメソッドの引数

未定義のメソッドにアクセスがあった場合、__callが呼ばれる

__call($name, $args){}

$nameはメソッド名,$argsは引数の連想配列

Singletonパターン

<?php
/**
 * Singletonパンターン
 *
 * @ex
 * $obj = Singleton::getInstance();
 * $obj->setName("test");
 * echo $obj->getName();
 */
class Singleton {
    private static $_singleton;
    private $_name;
    private function __construct() {
    }
    public static function getInstance() {
        if (!is_object(self::$_singleton)) {
            self::$_singleton = new Singleton();
        }
        return self::$_singleton;
    }
    public function setName($name) {
        $this->_name = $name;
    }
    public function getName() {
        return $this->_name;
    }
}

ライブラリをクラスで作る時はPSR-0を従う

http://d.hatena.ne.jp/hnw/20101006

インターフェイスを使う

  • index.php
<?php
require_once 'SampleLogic.php';
$logic = new SampleLogic();
$logic->execLogic();
  • SampleLogic.php
<?php
require_once 'InterfaceLogic.php';
class SampleLogic implements InterfaceLogic
{
  public function execLogic()
  {
    echo "exec";
  }
}
  • InterFaceLogic.php
<?php
interface InterfaceLogic
{
  public function execLogic();
}

namespace例(php ver5.3から

  • animal.php
<?php
namespace animal;
class Dog
{
  static public function call()
  {
     print "wan";
  }
}
  • main.php
<?php
namespace main;
require_once 'animal.php';
use animal;
echo \animal\Dog::call();  // wan