Question about Class Variable

What is the different between these two snippets…


class Controller {  
      public $model;   
   
      public function __construct()  {  
           [B]$this->model[/B] = new Model();  
      }   

and…


class Controller {  
      public $model;   
   
      public function __construct()  {  
           [B]$model[/B] = new Model();  
      }   

Aren’t they the same thing?

TomTees

In the first example the code is not in a class - valid.
In the second example the code is in a function in a class - valid.

In the examples you gave earlier the code was in the class but not in a function in that class, and that’s not allowed.

In a nutshell:


// I can place code here, outside a class
class X
{
  // I can't put code here
  function y()
  {
     // but I can place code here
  }
}

In theory yes. However, since logic is only allowed in functions in classes, both examples will give you a PHP error.

What then would be the difference between these two snippets…


class Controller {  
      public $model;
      [B]$this->model[/B] = new Model();  
      }   

and…


class Controller {  
      public $model;
      [B]$model[/B] = new Model();  
      }   

Aren’t they the same thing?

TomTees

Thanks for the clarification! :slight_smile:

(No wonder it is taking me so long to learn PHP and OOP?! I always seems to root out these little nuances?!)

TomTees

Hmmm… Interesting…

So what about this example I did yesterday. Is my code below wrong? (It seems to work?!)

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title></title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8">
		<link rel="stylesheet" type="text/css" href="index.css">
	</head>
	<body>
		<form method="post" action="time.php">
			<div>
				<input type="submit" name="btnSubmit" value="Time" class="btn" id="btnSubmit" />
			</div>
		</form>
	</body>
</html>

time.php


<?php
	include ('classes/class.time.php');

	echo '<pre>';
	print_r($_POST);
	echo '</pre>';

	[B][COLOR="Red"]$objTime = new Time;[/COLOR][/B]
	
	[B][COLOR="Red"]$currTime = $objTime->GenerateCurrentTime();
[/COLOR][/B]	
	echo "The current time is " . $currTime;
?>

class.time.php


<?php
	class Time {
		function GenerateCurrentTime(){
			[B][COLOR="Red"]$sTime = gmdate("d-m-Y H:i:s");[/COLOR][/B]
			return $sTime;
		}
	}
?>

TomTees

No they’re different.

In the first class you show the model is saved in a variable that is public in the class.
That is, once you’ve created an instance of the first Controller, you can call $controller->model and that will give you the model created in the constructor.

In the second class you show the model is saved in a variable local to the constructor, lot local to the class. So, if I were to create an instance of the second Controller class and call $controller->model i get NULL.

Makes sense?