출처 : http://www.sir.co.kr/bbs/board.php?bo_table=pl_php&wr_id=832&page=2 원본은 40 Tips for optimizing your php Code 1. If a method can be static, declare it static. Speed improvement is by a factor of 4. 2. echo is faster than print. 3. Use echo’s multiple parameters instead of string concatenation. 4. Set the maxvalue for your for-loops before and not in the loop. 5. Unset your variables to free memory, especially large arrays. 6. Avoid magic like __get, __set, __autoload 7. require_once() is expensive 8. Use full paths in includes and requires, less time spent on resolving the OS paths. 9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time() 10. See if you can use strncasecmp, strpbrk and stripos instead of regex 11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4 12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments. 13. It’s better to use select statements than multi if, else if, statements. 14. Error suppression with @ is very slow. 15. Turn on apache’s mod_deflate 16. Close your database connections when you’re done with them 17. $row[’id’] is 7 times faster than $row[id] 18. Error messages are expensive 19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time. 20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. 21. Incrementing a global variable is 2 times slow than a local var. 22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. 23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. 24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists. 25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. 26. Methods in derived classes run faster than ones defined in the base class. 27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations. 28. Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string. 29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments. 30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts. 31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. 32. Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request 33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick. Ex. Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length. 34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer. 35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. 36. Do not implement every data structure as a class, arrays are useful, too 37. Don’t split methods too much, think, which code you will really re-use 38. You can always split the code of a method later, when needed 39. Make use of the countless predefined functions 40. If you have very time consuming functions in your code, consider writing them as C extensions 41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview 42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80% 43. Excellent Article about optimizing php by John Lim
메쏘드가 static이 될 수 있다면 static으로 선언하라. 4배 빨라진다.
echo가 print보다 빠르다.
문자열을 이어붙이지 말고, echo를 이용하여 여러 개의 파라미터를 적어라.
for 루프을 위핸 최대값(탈출조건)을 루프 안에서가 아니고 루프 시작 이전에 지정하라.
메모리를 해제하기 위해 변수를 unset하라. 특히 커다란 배열은 그래야 된다.
__get, __set, __autoload와 같은 마법을 피해라.
require_once()는 비싸다.
include와 require를 사용할 때, 경로를 찾는데 시간이 적게 걸리는 full path를 사용하라.
스크립트가 언제 실행했는지 알고 싶으면 time()보다 $_SERVER[’REQUEST_TIME’]이 좋다.
정규표현식보다는 가능하면 strncasecmp나 strpbrk, stripos를 사용하라.
* 역주
strncasecmp: 두 문자열의 앞쪽 일부가 대소문자 구분없이 일치하는지 확인할 때 사용
strpbrk: 문자 집합에 속한 특정 문자가 문자열에 나타나는지 확인할 때 사용
stripos: 대소문자 구분없이 특정 문자열이 다른 문자열에 포함되는지 확인할 때 사용
str_replace가 preg_replace보다 빠르지만, strtr은 str_replace보다 4배 빠르다.
만약 문자열 교체 같은 함수가 배열과 문자열을 인자로 받아들이면, 그리고 그 인자 리스트가 길지 않다면, 배열을 한 번에 받아들여서 처리하는 것 대신에 한 번에 문자열을 하나씩 넘겨서 처리하는 것을 고려해봐라.
여러 개의 if/else if 문장 대신에 select 문장을 사용하는 게 더 좋다.
@를 이용한 에러 출력 방지는 매우 느리다.
Apache의 mod_deflate를 켜라.
*역주
mod_deflate는 서버의 출력을 클라이언트에게 보내기 전에 압축하는 모듈임
DB를 다 사용했으면 연결을 닫아라.
$row[’id’]가 $row[id]보다 7배 빠르다.
에러 메시지는 비싸다.
for 루프의 표현식 안에서 함수를 사용하지 마라.
for ($x = 0; $x < count($array); $x)에서 count() 함수가 매번 호출된다.
메쏘드 안에서 지역 변수를 증가시키는 것이 거의 함수 안에서 지역 변수를 호출(증가?)하는 것만큼 빠르다.
전역 변수를 증가시키는 것이 지역 변수를 증가시키는 것보다 2배 느리다.
객체의 멤버변수를 증가시키는 것이 지역 변수를 증가시키는 것보다 3배 느리다.
값이 지정되지 않은 지역 변수를 증가시키는 것이 미리 초기화된 변수를 증가시키는 것보다 9~10배 느리다.
전역 변수를 함수 안에서 사용하지 않으면서 그저 선언하기만 해도 (지역 변수를 증가시키는 것만큼) 느려진다. PHP는 아마 전역 변수가 존재하는지 알기 위해 검사를 하는 것 같다.
메쏘드 호출은 클래스 안에서 정의된 메쏘드의 갯수에 독립적인 듯 하다. 왜냐하면 10개의 메쏘드를 테스트 클래스에 추가해봤으나 성능에 변화가 없었기 때문이다.
파생된 클래스의 메쏘드가 베이스 클래스에서 정의된 것보다 더 빠르게 동작한다.
한 개의 매개변수를 가지고 함수를 호출하고 함수 바디가 비어있다면(함수 내부에서 아무것도 실행하지 않는다면) 그것은 7~8개의 지역변수를 증가시키는 것과 똑같은 시간을 차지한다. 비슷한 메쏘드 호출은 마찬가지로 15개의 지역변수를 증가시키는 연산쯤 된다.
문자열을 이중 따옴표 대신에 단일 따옴표로 둘러싸는 것은 좀 더 빠르게 해석되도록 한다. 왜냐하면 PHP가 이중 따옴표 안의 변수를 찾아보지만 단일 따옴표 안에서는 변수를 찾지 않기 때문이다. 물론 문자열 안에서 변수를 가질 필요가 없을 때만 이렇게 사용할 수 있다.
문자열을 echo할 때 마침표 대신에 쉼표로 분리하는 것이 더 빠르다.
주의: 이것은 여러 문자열을 인자로 받아들이는 함수인 echo로만 작동한다.
Apache에 의해 PHP 스크립트는 정적 HTML 페이지보다 최소 2에서 10배 느리게 서비스된다. 더 많은 정적 HTML 페이지와 더 적은 스크립트를 사용하려고 노력하라.
PHP 스크립트는 캐시되지 않으면 매번 재 컴파일된다. 컴파일 시간을 제거함으로써 25~100%만큼의 성능을 증가시키기 위해 PHP 캐싱 도구를 설치하라.
가능한 한 많이 캐시하라. memcached를 사용하라. memcached는 고성능 메모리 객체 캐싱 시스템이다.
문자열을 가지고 작업하며 문자열이 특정 길이인지 확인할 필요가 있을 때, strlen() 함수를 쓸 것이다. 이 함수는 계산없이 zval 구조체에서 사용할 수 있는 이미 알려진 문자열 길이를 반환하기 때문에 매우 빠르다. 그러나 strlen()이 함수이기 때문에 여전히 조금 느리다. 왜냐하면 함수 호출은 언급된 함수의 실행 뒤에 lowercase와 hashtable lookup같은 여러 개의 연산을 호출하기 때문이다. 어떤 경우에는 isset() 트릭을 이용하여 코드의 스피드를 증가시킬 수도 있다.
if (strlen($foo) < 5) { echo “Foo is too short”; }
vs.
if (!isset($foo{5})) { echo “Foo is too short”; }
isset()을 호출하는 것은 strlen()과는 달리 isset()이 언어 기본문법이고 함수가 아니기 때문에 함수 찾와 lowercase 작업을 필요로 하지 않으므로 strlen()보다 더 빠를 수도 있다. 이것은 가상적으로 문자열의 길이를 결정하는 실제 코드에 과부하가 없다는 것을 의미한다.
변수 $i의 값을 증가시키거나 감소키킬 때, $i++은 ++$i보다 조금 더 느릴 수 있다. 이것은 PHP의 특징이고 다른 언어에는 해당되지 않으니 좀 더 빨라질 것을 기대하면서 C나 Java 코드를 바꾸러 가지 마라. 안 빨라질 것이다. ++$i는 PHP에서 좀 더 빠른데 그것은 $i++에 4개의 opcode가 사용되는 대신에 3개만 필요하기 때문이다. 후증가는 사실 증가될 임시변수의 생성을 초래한다. 반면에 전증가는 원래 값을 직접 증가시킨다. 이것은 opcode가 Zend의 PHP optimizer처럼 최적화하는 최적화 기법의 하나이다. 모든 opcode optimizer들이 이 최적화를 수행하는 것은 아니고 많은 ISP와 server들이 opcode optimizer없이 수행되고 있기 때문에 명심하는 게 좋을 것이다.
모든 것이 OOP일 필요는 없다. 종종 그것은 너무 많은 과부하가 된다. 각각의 메쏘드와 객체 호출은 메모리를 많이 소비한다.
모든 데이터 구조를 클래스로 구현하지 마라. 배열도 유용하다.
메쏘드를 너무 많이 분리하지 마라. 어떤 코드를 정말 재사용할지 생각해봐라.
항상 메쏘드의 코드를 나중에 필요할 때 분리할 수 있다.
수많은 미리 정의된 함수를 활용해라.
매우 시간을 소비하는 함수가 있다면, C 확장으로 작성하는 것을 고려해봐라.
당신의 코드를 프로파일해봐라. 프로파일러는 코드의 어떤 부분이 가장 많은 시간을 소비하는지 보여준다. Xdebug 디버거는 이미 프로파일러를 포함하고 있다. 프로파일링은 전체적인 병목을 보여준다.
Apache 모듈로 사용가능한 mod_gzip은 실행 중에 데이터를 압축하여 전송할 데이터를 80%까지 줄일 수 있다.
John Lim의 PHP를 최적화하는 것에 관한 뛰어난 글
세번째 만든 바닐라향 초코칩 머핀

세번째 되서야 좀 머핀다운 머핀이 됐네요. 30정도 휴지를 시켰더니 딱 좋네요.
속이 촉촉한게 좋습니다. 온도조절을 조금 잘못해서 겉색깔이 좀 그을렸습니다.
초코칩이 무척 단데 다음엔 초코칩을 빼고 그냥 만들거나 무화과를 넣어봐야겠습니다.
알미늄틀 없이 했는데 적당히 부풀면서 나름 모양이 그냥 잡히네요.
바닐라향을 넣었는데 아주 살짝 향이 납니다.




티스토리 -> 텍스트큐브 트랙백 문제


좌측 사진 : 티스토리에서 텍스트큐브주소로 트랙백 보내기
우측 사진 : 글 작성시 에러 화면(티스토리)
텍스트큐브에서 티스토리나 네이버, 내부로 트랙백을 보내는 경우는 문제가 없습니다.
문제는 외부에서 텍스트큐브로 트랙백을 보낼때입니다.
제가 작성한 제로보드->태터툴즈 컨버터 글로 컨버팅을 하신 분이 트랙백을 보내셨다는데
휴지통이나 어디에도 내용이 남아있지 않아서 테스트를 해봤는데
현재 확인한 바로는 티스토리에서 텍스트큐브로 트랙백을 보낼 수 없습니다.
글 작성시 에러가 납니다.
텍스트큐브의 문제는 아닌 것 같습니다. 이글루스에서는 정상적으로 들어오고
텍스트큐브에서도 정상적으로 들어옵니다.
티스토리에서 해결해야할 문제인듯 합니다.
그리고 텍스트큐브에서 네이버 블로그로 트랙백 보낼 경우 문자셋이 깨져서 나옵니다.
네이버는 오로지 EUC_KR이죠.
받는 쪽이든 보내는 쪽이든 문자셋 확인후 서로 틀릴 경우 문자셋 변환을 시키면 될텐데
기본적인 것을 간과하네요.
[펌] 간단한 멀티파일 업로더
기본적인틀은 코드프로젝트에서 따왓는데 어딘지 잘 모르겟네요
스크립트 부분만 조금 수정 했습니다.
해당 위치에 uploads폴더를 만들어 줘야 합니다.
코드 프로젝트 소스에서 파일 추가(+ 버튼)을 누르면 그전에 있던 파일명들이 사라지는
현상 때문에 그부분만 고쳐서 올렸습니다.
최대 5개까지 업로드 가능 입니다.
기본적인 옵션들은 수정 하셔서 쓰시면 될듯합니다. ^^
<?php
if($_POST[‘pgaction’]==”upload”)
upload();
else
uploadForm();
//The form having dynamic file uploader
function uploadForm() {
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=euc-kr” />
<title> :: FILEUPLOAD :: </title>
</head>
<body bgcolor=”#C8C8C8″ leftmargin=”0″ topmargin=”0″ rightmargin=”0″ bottommargin=”0″>
<br>
<form name=”frm” method=”post” onsubmit=”return validate(this);” enctype=”multipart/form-data”>
<input type=”hidden” name=”pgaction”>
<?php if ($GLOBALS[‘msg’]) { echo ‘<center><span class=”err”>’.$GLOBALS[‘msg’].'</span></center>’; }?>
<input type=’button’ value=’추가’ onclick=’appendItem()’ />
<div id=’itemList’>
<input type=”file” name=”item_file[]”>
</div>
<input type=”submit” value=”Upload File”>
<div id=’debug’ style=”border:1px solid #000″></div>
</form>
<script type=’text/javascript’>
var count =0;
function appendItem()
{
count++;
if(count > 5)
{
alert(“더이상의 파일을 올릴수 없습니다.”);
count = 5;
}
else
{
//log(count);
var newSpanItem = document.createElement(“div”);
newSpanItem.setAttribute(“id”, “item_”+count);
var msg_str = ‘<input type=”file” name=”item_file[]”>’+ ‘<input type=”button” value =”삭제” onclick=”removeItem(‘+count+’)”> ‘;
//var msg_str =”ddd<br>”;
newSpanItem.innerHTML = msg_str;
var itemListNode = document.getElementById(‘itemList’);
itemListNode.appendChild(newSpanItem);
}
}
function removeItem(idCount)
{
var item = document.getElementById(“item_”+ idCount);
if(item != null)
{
item.parentNode.removeChild(item);
}
count –;
}
function validate(f)
{
var chkFlg = false;
for(var i=0; i < f.length; i++)
{
if(f.elements[i].type==”file” && f.elements[i].value != “”)
{
chkFlg = true;
}
}
if(!chkFlg)
{
alert(‘Please browse/choose at least one file’);
return false;
}
f.pgaction.value=’upload’;
return true;
}
</script>
</body>
</html>
<?php
}
//function to store uploaded file
function upload(){
if(count($_FILES[“item_file”][‘name’])>0)
{ //check if any file uploaded
$GLOBALS[‘msg’] = “”; //initiate the global message
for($j=0; $j < count($_FILES[“item_file”][‘name’]); $j++) { //loop the uploaded file array
$filen = $_FILES[“item_file”][‘name’][“$j”]; //file name
$path = ‘uploads/’.$filen; //generate the destination path
if(move_uploaded_file($_FILES[“item_file”][‘tmp_name’][“$j”],$path)) { //upload the file
$GLOBALS[‘msg’] .= “File# “.($j+1).” ($filen) uploaded successfully<br>”; //Success message
}
}
}
else
{
$GLOBALS[‘msg’] = “No files found to upload”; //Failed message
}
uploadForm(); //display the main form
}
?>
[펌] 간단하게 구현하는 PHP 클래스에서의 메소드 체이닝
[알고리즘] 간단하게 구현하는 PHP 클래스에서의 메소드 체이닝
글쓴이 kirrie 날 짜 09-01-30 15:40 조 회 1004
PHP5 버전에서만 메소드체이닝이 가능합니다.
—>
http://phpschool.com/gnuboard4/bbs/board.php?bo_table=talkbox&wr_id=1389304&page=3
에서 JQuery의 메소드체이닝에 관한 jscript님의 글을 읽었습니다. 같은 테크닉이 PHP 클래스에서도 가능합니다.
메소드체이닝을 하는 가장 큰 이유는 아마도 오브젝트에 대한 빈번한 접근을 줄임으로써 퍼포먼스 향상에 약간의 이득을 볼 수 있다는 점일 것입니다. (이 부분에 대한 명확한 증거는 없습니다만, 왠지 그럴 것 같다능 -_-;; 구글링 해봐도 딱히 퍼포먼스나 리소스 관리에 효율적이라는 자료는 찾아 볼 수가 없네요.) 게다가 부가적으로는 (저는 퍼포먼스보다 이게 더 중요하다고 보지만) 시멘틱한 코드를 짤 수 있다는 장점도 있습니다.
간단한 예를 들어보겠습니다. 계산기 클래스입니다.
class Calc {
var $amount;
function plus($num) {
$this->amount += $num;
return $this;
}
function minus($num) {
$this->amount -= $num;
return $this;
}
function equal() {
return $this->amount;
}
}
$calc = new Calc;
// 1. 기존 방법을 사용해서 4 + 3 – 2를 계산함
$calc->plus(4);
$calc->plus(3);
$calc->minus(2);
echo $calc->equal(); // 5
// 2. 메소드체이닝을 사용해서 4 + 3 – 2를 계산함
echo $calc->plus(4)->plus(3)->minus(2)->equal(); // 5
메소드체이닝을 이용하니 코드량이 팍 줄었고 매우 인간 친화적인 코드가 나왔습니다.
구현 방법은 매우 간단합니다. 메소드체이닝을 적용할 메소드에서 오브젝트를 리턴하기만 하면 됩니다.
문제점이라고 한다면, 아마도 정교한 에러 핸들링 정책이 없다면 에러 발생시에 정확히 어디에서 발생했고 무엇때문에 발생했는지를 식별하기가 쉽지 않다는 것입니다. 한 라인에 걸쳐서 작성되는 코드기 때문이죠. 구더기 무서워서 장 못담그겠습니까만은..
주로 데이터베이스 클래스에서 사용하면 좋습니다. 이것도 예를 들어보지요.
“SELECT id, name, hobby, job FROM user WHERE id = ‘1’”
위의 쿼리를 기 작성된 메소드체이닝이 구현된 데이터베이스 클래스에서 사용한다고 하면 (클래스는 작성하지 않겠습니다.)
$db->select(‘id, name, hobby, job’)->from(‘user’)->where(‘id’, 1)->execute();
이렇게 작성할 수 있습니다.
[그리고 PHP4에서도 사용할 수 있었던 것으로 기억하는데, 확실하지는 않습니다. 혹시 PHP4버전을 사용중이신 분은 테스트 부탁드립니다.] <- X
PHP5에서만 동작합니다.
License
본 게시물은 GPL을 따릅니다. [ GPL 안내 ]
산수익힘 09-01-30 16:37
따로 구현을 해줘야 작동하는줄 알았는데 PHP5에서는 그냥 쓰면 되는거였군요.
이렇게 코딩하는 방법이 있었다니 미쳐 생각 못했네요 +_+;;
당장 지금 만들고 있는 클래스에 적용시켜야 겠어요~
본내용글과 관련되서 검색해서 찾아봤는데 PHP4에서는 쓸수 없다고 합니다.
요약하자면 PHP4에서 객체는 값으로 전달 되었지만 PHP5 부터는 참조로 전달되기때문에
PHP4에서는 함수에서 반환된 객체를 참조하기 힘들다 라고 하네요.
따로 구현을 해줘야 작동하는줄 알았는데 PHP5에서는 그냥 쓰면 되는거였군요.
이렇게 코딩하는 방법이 있었다니 미쳐 생각 못했네요 +_+;;
당장 지금 만들고 있는 클래스에 적용시켜야 겠어요~
본내용글과 관련되서 검색해서 찾아봤는데 PHP4에서는 쓸수 없다고 합니다.
요약하자면 PHP4에서 객체는 값으로 전달 되었지만 PHP5 부터는 참조로 전달되기때문에
PHP4에서는 함수에서 반환된 객체를 참조하기 힘들다 라고 하네요.
kirrie 09-01-30 19:40
네, 저도 찾아보니 PHP5부터 가능하다고 되어 있네요. (그런데 대체 4에서도 될꺼라는 생각은 어떻게 하게 된건지… -_-;;)
네, 저도 찾아보니 PHP5부터 가능하다고 되어 있네요. (그런데 대체 4에서도 될꺼라는 생각은 어떻게 하게 된건지… -_-;;)
머가좋은건가요? 09-01-30 17:18
echo $calc->plus(4)->plus(3)->minus(2)->equal(); // 5
이런 코드 제 가슴에 꽉 박히네요
잘배웠습니다.
echo $calc->plus(4)->plus(3)->minus(2)->equal(); // 5
이런 코드 제 가슴에 꽉 박히네요
잘배웠습니다.
송효진 09-01-30 18:42
객체 자신을 계속 체이닝 하는 패턴 자체가 쉽게 나오지 않더군요.
그래서 잘 안쓰게됩니다.
뭔가 실전예제 같은게 있으면 더 좋을것 같네요.
자신이 아닌 객체를 리턴하는것을 체이닝 비슷하게 쓰기는 합니다.
$rows = $db->query(‘SELECT * FROM table LIMIT 5’)->fetchAll();
객체 자신을 계속 체이닝 하는 패턴 자체가 쉽게 나오지 않더군요.
그래서 잘 안쓰게됩니다.
뭔가 실전예제 같은게 있으면 더 좋을것 같네요.
자신이 아닌 객체를 리턴하는것을 체이닝 비슷하게 쓰기는 합니다.
$rows = $db->query(‘SELECT * FROM table LIMIT 5’)->fetchAll();
행복한고니 09-01-30 19:17
PHP4에서만 해보고 안되는 줄 알았는데, PHP5에선 되는거였군요.
PHP4에서만 해보고 안되는 줄 알았는데, PHP5에선 되는거였군요.
낭망백수 09-01-30 21:17
결합된 객체나 객체 집합 iterator 구현하다보면 유용하겠네요.
감사합니다. 꾸벅~!
결합된 객체나 객체 집합 iterator 구현하다보면 유용하겠네요.
감사합니다. 꾸벅~!
ⓧ【태미™】 09-01-30 21:20
좋군요. ^^
좋군요. ^^
돈이최고 09-01-30 22:06
php로도 메소드체이닝을 구현한다는게 흥미롭습니다.
자바스크립트 프레임워크 jquery는 메소드체이닝이 자주 유용하게 쓰이는 사례로 손꼽히죠.
자바스크립트로 DOM을 수정하는 것은 메소드체이닝을 활용할수있는 사례가 무궁무진하지만,
그런데 송효진님 말대로 php에서는 메소드체이닝해서 도움이 될만한 패턴사례가 있을지 궁금합니다.
php로도 메소드체이닝을 구현한다는게 흥미롭습니다.
자바스크립트 프레임워크 jquery는 메소드체이닝이 자주 유용하게 쓰이는 사례로 손꼽히죠.
자바스크립트로 DOM을 수정하는 것은 메소드체이닝을 활용할수있는 사례가 무궁무진하지만,
그런데 송효진님 말대로 php에서는 메소드체이닝해서 도움이 될만한 패턴사례가 있을지 궁금합니다.
다래아빠 09-01-31 09:22
윗분들 말씀대로 php에서 체이닝 쓸 일이 그리 많지는 않을 거 같네요.
좋은 팁 감사드립니다. 🙂
윗분들 말씀대로 php에서 체이닝 쓸 일이 그리 많지는 않을 거 같네요.
좋은 팁 감사드립니다. 🙂
kirrie 09-01-31 14:04
데이터베이스 클래스를 제외하고는 딱히 ‘이거다’ 싶은 것은 발견하지 못했습니다.
__call 과 같은 매직 메소드를 이용해서 동적으로 멤버변수에 값을 할당하는 경우에는 체이닝을 이용해도 좋을 것 같기도 하구요. 간단한 예제입니다. ( http://codepad.org/Tsqig92W 에 가시면 실행 모습을 확인할 수 있습니다.)
<?
class MethodChaining {
var $data = array();
function __call($name, $args)
{
$prefix = strtolower(substr($name, 0, 3));
$postfix = strtolower(substr($name, 3, strlen($name)));
switch($prefix)
{
case ‘get’:
return isset($this->data[$postfix]) ? $this->data[$postfix] : false;
break;
case ‘set’:
if(!empty($args))
$this->data[$postfix] = count($args) == 1 ? $args[0] : $args;
return $this;
break;
}
}
}
$chain = new MethodChaining;
echo $chain->setInteger(1)->getInteger(); // 1
echo $chain->setString(‘hello, world’)->getString(); // hello, world
?>