User Tools

Site Tools


php:kompost:varinclass

[PHP] Variablen innerhalb und ausserhalb von Klassen

<?php
 
$globalVar = 123;
 
class MyParent{
	var $varP1 = "parent1";
	var $varP2;
 
	public function __construct($var2){
		$this->varP2 = $var2;
	}
}
 
class MyClass extends MyParent {
 
	private $var1;
 
	public function __construct($var2){
		parent::__construct("Parent_{$var2}");
		$this->var1 = $var2;
	}
 
	public function getVar(){
		return $this->var1;
	}
 
	public function step0(){
		$this->addLine("step 0", '$this->var1', $this->var1);
		$this->addLine("step 0", '$var1', $var1);
		$this->addLine("step 0", '$var2', $var2);
	}
 
	public function step1(){
		$this->addLine("step 1", '$this->var1 + $globalVar', "{$this->var1}_{$globalVar}");
	}
 
	public function step2(){
		global $globalVar;
		$this->addLine("step 2", '$this->var1 + $globalVar', "{$this->var1}_{$globalVar}");
	}
 
	public function step3(){
		$this->addLine("step 3", '$this->var1 + $GLOBALS[globalVar]', "{$this->var1}_{$GLOBALS['globalVar']}");
	}
 
	public function step4(){
		$this->addLine("step 4", '$this->varP1', $this->varP1);
		$this->addLine("step 4", '$this->varP2', $this->varP2);
	}
 
	private function addLine($step, $name, $value){
		echo "[{$step}] {$name}: {$value}<br />";	
	}
 
}	
 
$myObject = new MyClass("abc");
 
$myObject->step0();
$myObject->step1();
$myObject->step2();
$myObject->step1();
$myObject->step3();
$myObject->step4();
 
echo $myObject->varP1;
$myObject->varP1 = 123456;
echo $myObject->varP1;
 
?>

Kategorien: CatPhp

php/kompost/varinclass.txt · Last modified: 11.12.2013 14:22:36 (external edit)