“Klasa PHP” Kod odpowiedzi

Jak zrobić klasę w PHP

<?php
class house {
  public $color;
  public $land;	
  public function __construct($color, $land) {
    $this->color = $color;
    $this->land = $land;
  }
  public function message() {
    return "My house is " . $this->color . " in color and occupies" . $this->model . " of land!";
  }
}

$House = new house("black", "40 meter squares");
echo $House -> message();
echo "<br>";
$House = new house("red", "30 meter square");
echo $House -> message();
?>

//Another example:

class Fruit {
  public $fruitname;
  public $type;
  public function __construct($fruitname, $type) {
    $this->color = $fruitname;
    $this->model = $type;
  }
  public function message() {
    return "The fruit is a " . $this->fruitname . "and in type, " . $this->type;
  }
}

$Fruit = new Car("mango", "Carabao");
echo $Fruit -> message();
echo "<br>";
$Fruit = new Car("apple", "Red Delicious");
echo $Fruit -> message();
?>
Rick Astley

Klasa PHP


/*PHP 5 is very very flexible in accessing member variables and member functions. 
These access methods maybe look unusual and unnecessary at first glance; 
but they are very useful sometimes; 
specially when you work with SimpleXML classes and objects. 
I have posted a similar comment in SimpleXML function reference section, 
but this one is more comprehensive.

I use the following class as reference for all examples:
*/

<?php

class Foo {

    public $aMemberVar = 'aMemberVar Member Variable';
    public $aFuncName = 'aMemberFunc';


    function aMemberFunc() {
        print 'Inside `aMemberFunc()`';
    }
}
$foo = new Foo;
?>
/*You can access member variables in an object using another variable as name:*/

<?php
$element = 'aMemberVar';
print $foo->$element; // prints "aMemberVar Member Variable"
?>
or use functions:

<?php

function getVarName()
{ return 'aMemberVar'; }
print $foo->{getVarName()}; // prints "aMemberVar Member Variable"

?>



//Important Note: You must surround function name with { and } 
  ///or PHP would think you are calling a member function of object "foo".
//you can use a constant or literal as well:

<?php

define(MY_CONSTANT, 'aMemberVar');

print $foo->{MY_CONSTANT}; // Prints "aMemberVar Member Variable"

print $foo->{'aMemberVar'}; // Prints "aMemberVar Member Variable"

?>
//You can use members of other objects as well:

<?php

print $foo->{$otherObj->var};

print $foo->{$otherObj->func()};

?>

//You can use mathods above to access member functions as well:

<?php

print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"

print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"

?>

Azizul7m

Odpowiedzi podobne do “Klasa PHP”

Pytania podobne do “Klasa PHP”

Więcej pokrewnych odpowiedzi na “Klasa PHP” w PHP

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu