> php教程 > php手册 > [转]类与PHP (II)

[转]类与PHP (II)

WBOY
풀어 주다: 2016-06-21 09:13:07
원래의
1147명이 탐색했습니다.

Classes and PHP

When you create a function within a class with the same name as the class that function will execute whenever you create an object of that class. This is called a 'constructor.' It allows me to have default values for each attribute automatically whenever I create an object:



You define an instance of a class by giving it a name ($Basic) and assigning it "=new ClassName;".

You could also send different values for the variables as arguments when declaring the new Style, but if you declare a value you have to declare all of them that occur to the right of the one you declare (class functions work just like regular functions in this respect). Meaning if you set 'text' to something different than the default given in Style, then you have to declare all the variables. There is an easier way. We can create a function that changes a single variable within the class:


Function Set($varname,$value) {

        $this->$varname=$value;

}

?>

So to change the value of particular variable of an instance we can:

Set('size','2'); ?>

You use the "->" operator to refer to a variable or a function of an instance. So the above tells the interpreter "Run function 'Set()' of instance '$Basic'." It knows that "$Basic" is an instance of class "Styles" because we declared it so. Similarly we can refer to variables of an instance in the same manner (e.g. $Basic->text).

Let's create a Style for table headers that has some slightly different attributes.


$Theader= new Style;
$Theader->Set('text','#0000FF');
$Theader->Set('bgcol','#000000');

?>

There, that's good enough. Now my table header has blue text on a black background. I want my table body to be a slightly lighter gray than my main page, black is good for text, but maybe I'll make the text smaller:


$Tbody=new Style;
$Tbody->Set('bgcol','#AAAAAA');
$Tbody->Set('size',2);

?>



관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿