2016-09-06 4 views
2

매우 간단한 클래스 나 모델을 작성하고 cfscript에서 사용하는 간단한 예제를 찾을 수 없습니다. 여기 cfscript에서 클래스/객체를 만들고 사용하는 방법은 무엇입니까?

는 PHP, 내가 원하는 무엇인가 : oocaller.php :

<?php 
include 'oo-model.php'; 
$dog = new animal('dog'); 
echo $dog->says(); 

OO-모델 :

<?php  
class animal{ 
    public $type; 

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

    function says(){ 
     if($this->type == 'dog') 
      return 'woof!'; 
     if($this->type == 'cat') 
      return 'meow!';   
     return 'I dont know what to say!'; 
    } 
} 

확인이 작동 ...

oocaller.cfm :

<cfscript> 
//include 'oomodel.cfc'; //dont need, autoincluded 
//obj = new admin.d.oomodel(); //for path, use dots not slashes... 
//obj = CreateObject("component", "oomodel");   
obj = CreateObject("component", "/admin/d/oomodel");//either works   
obj.out(); 
writeoutput('<HR>'); 
writedump(obj.other); 
writeoutput('<HR>'); 
writedump(obj); 
</cfscript> 

로 : oomodel.cfc :

component { 
    thevar = 'thevrrrrr'; 
    this.other = 'otherrrr'; 
    public function out(){ 
     writeoutput(variables.thevar & "<BR>"); 
     writeoutput(thevar   & "<BR>"); 
     writeoutput(this.other  & "<BR>"); 
    } 
} 
+3

이 구성 요소는 자체에 포함 된 "클래스"해야합니다 : 당신은 그냥 ColdFusion과 함께 시작처럼

내가 제안 할 수 있습니다, 보이는 중괄호. 그런 다음 구성 요소를 별도의 파일 (cfm 템플릿 또는 다른 구성 요소)에서 객체로 인스턴스화합니다. 또한 구성 요소 블록 외부의 코드를 별도의 파일로 이동하면 태그를 제거 할 수 있습니다. 구성 요소는 스크립트로 전체적으로 작성 될 수 있습니다. –

답변

3

하면 this에 대한 같은 test.cfm

<cfscript> 
obj = new d();  
obj.out();  
</cfscript> 

에 다음과 같은 저장 d.cfc

component displayname="d" output="false" { 
    public function out(){ 
     writeoutput('blahblahblah'); 
    } 
} 

에 다음 저장, 모든 운반 범위는 공개 메서드 및 속성 일반적으로 개인용 변수의 범위를 지정할 필요는 없지만 명시적이고 안전하며 성능의 마지막 부분을 얻으려면 variables.theVar을 사용해야합니다. Varibales은 모든 개인적인 메서드와 속성을 전달하는 범위입니다.

적절한 생성자를 작성하려면 init() 함수를 사용하십시오. 닫는 곱슬 다음 아무것도,

+1

괜찮아요, displayname은 다음, superflous입니까? 클래스의 이름은 파일의 이름입니까? 또한, apparantly, 그것을 포함하지 않고 자동으로 클래스를로드합니다. 또한 :'new d()'는'CreateObject ("component", "d")와 완전히 동일합니다. '? –

+1

예,'new d()'는'createObject ('component', 'd';')와 동일합니다. 클래스를 "가져 오는"동안,'new' 선언은 클래스의 경로입니다. 위의 예제에서'd'가 루트 폴더에 있거나'new d()'를 호출하는 코드와 동일한 폴더에 있다고 가정합니다 .. obj = new path.to.d ();''d.cfc'는'path/to' 폴더에 있습니다. – beloitdavisja

+0

수정 된 질문을 참조하십시오 ... 나는 호출/cfc 부분을 알아 냈지만 'this'가 아닙니다. –

관련 문제