2018年9月26日 星期三

jq 偌多個組件需要統一使用 queue

// queue 的統一者
            const queue_1 = {
                name: "queue"
            };
            function t_1() {
                $(queue_1).queue(function (next) {
                    $("#box_1").animate({
                        left: "+=5%"
                    }, {
                        duration: 1000,
                        queue: false,
                        complete: function () {
                            next();
                        }
                    })
                });
            }

2018年9月23日 星期日

2018年9月1日 星期六

php 設置網頁過期時間

$max_age = $expiration - $_SERVER['REQUEST_TIME'];

// $_SERVER['HTTP_IF_MODIFIED_SINCE'] (If-Modified-Since)瀏覽器對cache的詢問
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $this->set_status_header(304);
    exit;
}

// 編輯提示
header('Pragma: public|no-cache');

// http1.1的 cahe control
header('Cache-Control: max-age=' . $max_age . ', public');

// 過期時間
header('Expires: ' . gmdate('D, d M Y H:i:s', $expiration) . ' GMT');
      
// 最後修改時間(若最後編輯時間比cache更接近,就停用 cache)
header('Last-modified: ' . gmdate('D, d M Y H:i:s', $last_modified) . ' GMT');

  1. ExpiresCache-Control: max-age決定這份快取的「新鮮度」,也就是什麼時候「過期」。在過期之前,瀏覽器「不會」發送出任何 Request
  2. 當快取過期之後,可以用If-Modified-Since或是If-None-Match詢問 Server 有沒有新的資源,如果有的話就回傳新的,沒有的話就回傳 Status code 304,代表快取裡面的資源還能繼續沿用

2018年8月29日 星期三

php 正則易碰到的問題

$s = '/a/b';

printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\//', '@', $s);

printf('<p>%s</p><hr>', $res);

//----------------------------

$s = '\\a\\b';
printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\\\\/', '@', $s);

printf('<p>%s</p><hr>', $res);
//----------------------------

$s = '\a\b';
printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\\\\/', '@', $s);

printf('<p>%s</p><hr>', $res);
----------------------------------------------------------

'/\\\\/' => php string = /\\/ => reg = /\/(匹配 '\')
'///' => php string = /// =>  reg = error
'/\//' => php string = /\// => reg = ///(匹配 '/')

----------------------------------------------------------
對 php preg來說  (/) 也屬於保留字
 ----------------------------------------------------------

PHP的跳脫字元



 對 "" 來說,對''無用
\$    顯示金錢符號 $
\"    顯示雙引號符號 "
\'    顯示單引號符號 '
\\    顯示倒斜線符號 \
\b    Backspace鍵
\n    換行符號<br>
\r    Return 歸位字元
\t    Tab鍵
\000 ~ \377    以16進位表示某一個字元
\x00 ~ \xFF    以8進位表示某一個字元

單引號 ' ' 是連跳脫字元都不處理,也就是 \n 會當成 \ 和 n ,而不是換行!這點要特別注意!很多 bug 就是由此而來,例如 str_replace \n 沒有作用之類的。
附帶一提,雖然單引號 ' ' 裡面不處理跳脫字元,但在單引號 ' ' 裡面要寫 (') 或 (\) 還是要記得跳脫一下,不然 PHP 會無法判斷字串結尾︰
<?php
  echo '\''; // 會印 '
  echo '\\'; // 會印 \
?> 
 

PHP preg_quote() 函數

PHP 正則表達式(PCRE)PHP 正則表達式(PCRE)
preg_last_error 函數用於轉義正則表達式字符。

語法

string preg_quote ( string $str [, string $delimiter = NULL ] ) preg_quote() 需要參數 str 並向其中 每個正則表達式語法中的字符前增加一個反斜線。 這通常用於你有一些運行時字符串 需要作為正則表達式進行匹配的時候。
正則表達式特殊字符有: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
參數說明:
  • $str: 輸入字符串。
  • $delimiter: 如果指定了可選參數 delimiter,它也會被轉義。這通常用於 轉義 PCRE 函數使用的分隔符。 / 是最通用的分隔符。

返回值

返回轉義後的字符串。

實例

實例 1

<?php  
    $keywords = '$40 for a g3/400';
    $keywords = preg_quote($keywords, '/')
    echo $keywords
?>
執行結果轉義了 $ 和 / 特殊字符,如下所示:
返回 \$40 for a g3\/400

將文本中的單詞替換為斜體

<?php //在這個例子中,preg_quote($word) 用於保持星號原文涵義,使其不使用正則表達式中的特殊語義。 $textbody = "This book is *very* difficult to find."; $word = "*very*"; $textbody = preg_replace ("/" . preg_quote($word) . "/", "<i>" . $word . "</i>", $textbody); echo $textbody; ?>
執行結果如下所示:
This book is <i>*very*</i> difficult to find.
 



2018年8月26日 星期日

php 取得檔案資訊

[PHP] 取得檔案的資訊(檔案、路徑...等等) 或 網頁的目錄(或根目錄)

當我們需要用PHP網頁進行一些檔案操作,我們需要知道相關檔案名稱、目錄名稱或存放位置...等資訊,所以PHP有提供一些函式讓我們可以取得這些資訊...
假設我們的網頁是放在根目錄下的test資料夾中,檔案名稱為myweb.php

1、取得目前網頁的檔案路徑及檔案名稱:
$path=$_SERVER[PHP_SELF];
echo $path; //輸出結果:/test/myweb.php

2、利用pathinfo()搭配$path取得更多資訊:
$path_parts = pathinfo($path);  //這邊的$path_parts會是一個陣列,裡面的元素就是我們要的資訊。
echo $path_parts['dirname'];  //輸出結果:/test
echo $path_parts['basename'];  //輸出結果:myweb.php
echo $path_parts['extension'];  //輸出結果:php
echo $path_parts['filename'];  //輸出結果:myweb

3、取得真實的電腦存放位置:
echo realpath($path['basename']);  //輸出結果:C:\AppServ\www\test\111.php

4、取得網頁的目錄、根目錄或路徑
應用方式舉例如下,請自行搭配各種變數去套用
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$x;

2018年8月21日 星期二

php 一些取得 object 資訊的 API


get_class(): 取得物件的 className

get_parent_class(): 取得物件繼承者的 className

get_object_vars():  返回類中所有的非靜態屬性

get_class_methods(): 函數的作用是返回由類的方法名組成的數組

2018年7月26日 星期四

php 取得請求的方法

class G {

    public $NOW_TIME;
    public $REQUEST_METHOD;
    public $IS_GET;
    public $IS_POST;
    public $IS_PUT;
    public $IS_DELETE;
    public $IS_AJAX;

    public function __construct() {
        $this->NOW_TIME = $_SERVER['REQUEST_TIME'];
        $this->REQUEST_METHOD = $_SERVER['REQUEST_METHOD'];
        $this->IS_GET = ($this->REQUEST_METHOD == 'GET' ? true : false);
        $this->IS_POST = ($this->REQUEST_METHOD == 'POST' ? true : false);
        $this->IS_PUT = ($this->REQUEST_METHOD == 'PUT' ? true : false);
        $this->IS_DELETE = ($this->REQUEST_METHOD == 'DELETE' ? true : false);

        $ajax_var = 'ajax';
        $postAjax = isset($_POST[$ajax_var]) && $_POST[$ajax_var] == 1 ? true : false;
        $getAjax = isset($_POST[$ajax_var]) && $_POST[$ajax_var] == 1 ? true : false;
        $commonAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false;


        $this->IS_AJAX = ($commonAjax || $postAjax || $getAjax) ? true : false;

        }

}

2018年7月25日 星期三

php 讓 container 注入模組的方式

class Container {

    public $name = 'a';
    public $age = 19;
    public $load;

    public function __construct() {
        $this->load = new Loader($this);
    }

    public function getName() {
        printf('<p>%s</p>', $this->name);
    }

}

// 注入模組
class Loader {
    public $container;

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

    public function __get($name) {

        if (isset($this->container->$name)) {
            return $this->container->$name;
        }

    }

}

$a = new Container();

$load = $a->load;
var_dump($load->name);

2018年7月20日 星期五

php 取得最上層的 className

function getParentClassName($o) {
    $res = $o;

    while (TRUE) {

        $ref = new ReflectionClass($res);
        $r = $ref->getParentClass();

        if ($r) {
            $ref = $r;
        } else {
            break;
        }
        // className
        $res = $ref->getName();
    }

    return $res;
}

2018年7月9日 星期一

javascript.....判斷 global

/** Detect free variable `global` from Node.js. */
  var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

  /** Detect free variable `self`. */
  var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

  /** Used as a reference to the global object. */
  var root = freeGlobal || freeSelf || Function('return this')();
---------------------------------------------------------------------------------------------------
 // node.js

if (typeof exports != 'undefined' && !exports.nodeType) {
        if (typeof module != 'undefined' && !module.nodeType && module.exports) {
            exports = module.exports = _;
        }
        exports._ = _;
    } else {
        root._ = _;
    }






---------------------------------------------------------------------------------------------------
// node.js

  /** Detect free variable `exports`. */
  var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

  /** Detect free variable `module`. */
  var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

  /** Detect the popular CommonJS extension `module.exports`. */
  var moduleExports = freeModule && freeModule.exports === freeExports;

  /** Detect free variable `process` from Node.js. */
  var freeProcess = moduleExports && freeGlobal.process;

  /** Used to access faster Node.js helpers. */
  var nodeUtil = (function() {
    try {
      // Use `util.types` for Node.js 10+.
      var types = freeModule && freeModule.require && freeModule.require('util').types;

      if (types) {
        return types;
      }

      // Legacy `process.binding('util')` for Node.js < 10.
      return freeProcess && freeProcess.binding && freeProcess.binding('util');
    } catch (e) {}
  }());
---------------------------------------------------

var root = this
// AMD / RequireJS
if (typeof define !== 'undefined' && define.amd) {
    define([], function () {
        return async;
    });
}
// Node.js
else if (typeof module !== 'undefined' && module.exports) {
    module.exports = async;
}
// included directly via <script> tag
else {
    root.async = async;
}

2018年6月30日 星期六

php(ReflectionClass)(反射) 從一個實力的物件取得類別方法,並執行

ReflectionClass:
     public static string export()  //打印类的详细信息
     public string getName()        //取得类名或接口名
     public bool isInternal()       //类是否为系统内部类
     public bool isUserDefined()    //类是否为用户自定义类
     public bool isInstantiable()   //类是否被实例化过
     public bool hasMethod(string name)  //类是否有特定的方法
     public bool hasProperty(string name)//类是否有特定的属性
     public string getFileName()         //获取定义该类的文件名,包括路径名
     public int getStartLine()           //获取定义该类的开始行
     public int getEndLine()             //获取定义该类的结束行
     public string getDocComment()       //获取该类的注释
     public ReflectionMethod getConstructor()           //取得该类的构造函数信息
     public ReflectionMethod getMethod(string name)     //取得该类的某个特定的方法信息
     public ReflectionMethod[] getMethods()             //取得该类的所有的方法信息
     public ReflectionProperty getProperty(string name) //取得某个特定的属性信息
     public ReflectionProperty[] getProperties()        //取得该类的所有属性信息
     public array getConstants()                        //取得该类所有常量信息
     public mixed getConstant(string name)              //取得该类特定常量信息
     public ReflectionClass[] getInterfaces()           //取得接口类信息
     public bool isInterface()  //测试该类是否为接口
     public bool isAbstract()   //测试该类是否为抽象类
-----------------------------------------------------------------------
 class X{
    public static function go(){
        echo '<h1>go</h1>';
    }
    
    public function gogo(){
        echo '<h1>gogo</h1>';
    }
}

class Y extends X {
    
}
//==============================================================================
$y = new Y();

// 取得 static
$className = get_parent_class($y);
$ref = new ReflectionMethod($className, 'go');
$ref->invoke(NULL);
//============================================================================== 
 function make($class, $vars = array()) {
    $ref = new ReflectionClass($class);

    if(!$ref->isInstantiable()) {
        throw new Exception("类{$class} 不存在");
    }

    // 取得建構式
    $constructor = $ref->getConstructor();
    if(is_null($constructor)) {
        return new $class;
    }

    // 確定建構式的參數
    $params = $constructor->getParameters();
    
    $resolveParams = array();
    
    foreach ($params as $key=>$value) {
        $name = $value->getName();
        
        if(isset($vars[$name])) {
            $resolveParams[] = $vars[$name];
        } else {
            
            // 參數是否有默認值
            $default = $value->isDefaultValueAvailable() ? $value->getDefaultValue() : null;
            
            if(is_null($default)) {
                // 參數沒有默認值
                
                if($value->getClass()) {                    
                    
                    // 遞迴(這點似乎有點多)
                    $resolveParams[] = make($value->getClass()->getName(), $vars);
                } else {
                    throw new Exception("{$name} 没有传值且没有默认值。");
                }
            } else {
                $resolveParams[] = $default;
            }
        }
    }

    return $ref->newInstanceArgs($resolveParams);
} 

php &fn

Example1>>

<?php
function &_copy(){
   
    // 函數(&)的目的
    static $data = array();
    return $data;
}


// 呼叫函數還是需要&
$a = &_copy();
$a[] = 5;

// 呼叫函數還是需要&
$b = &_copy();

var_dump($a);
var_dump($b);
------------------------------------------------
Example2>>

function &xyz(Array &$d){
    return $d;
}

$data_1 = array(5, 1, 6);
$data_2 = &xyz($data_1);
//----------------------------
var_dump($data_2);
//----------------------------
sort($data_1);
var_dump($data_2);