Hi everyone, i am closing my recent problems with some code, this should be the last doubt, thanks for all the helpers in recent doubts that i created.
well, the code is here:
main.php
PHP Code:
<?php
require_once 'functions.php';
$Var = 1;
$UserFunctions = new User();
$UserFunctions->MyVar();
?>
functions.php
PHP Code:
class User {
public function MyVar() {
if ($Var == 1) {
echo "Yes";
}
else {
echo "no";
}
}
}
well, it give a error on functions.php and say "Undefined variable:Var"
This part is really very important, anyone can give me some help? Thanks community
When you're inside the scope of a function you CAN NOT see variables defined in the global scope (without defining them as "global").
Perhaps rewriting that variable into the constructor would help:
PHP Code:
class User {
private $myVar;
public function __construct($myVar) {
$this->myVar = $myVar;
}
public function myVar() {
return $this->myVar == 1 ? true : false;
}
}
foreach(array(new User(1), new User(3)) as $user)
echo ($user->myVar() === true ? "yes" : "no"), "\n";
But basically, you're completely ignoring the SCOPE. OOP/SCOPE is important because it helps with encapsulation. Although, traditionally programming was "data structures" and "functions"; OOP combines both of these into a single "class".
Edit: not everything I said here is 100% true, there are some hacks in PHP that I did not mention; but I suspect they'll only make a HUGE mess out of your code.
Last edited by eval(BadCode); 08-03-2012 at 08:22 PM.
I use (, ; : -) as I please- instead of learning the English language specification: I decided to learn Scheme and Java;
When you're inside the scope of a function you CAN NOT see variables defined in the global scope (without defining them as "global").
Perhaps rewriting that variable into the constructor would help:
PHP Code:
class User {
private $myVar;
public function __construct($myVar) {
$this->myVar = $myVar;
}
public function myVar() {
return $this->myVar == 1 ? true : false;
}
}
foreach(array(new User(1), new User(3)) as $user)
echo ($user->myVar() === true ? "yes" : "no"), "\n";
But basically, you're completely ignoring the SCOPE. OOP/SCOPE is important because it helps with encapsulation. Although, traditionally programming was "data structures" and "functions"; OOP combines both of these into a single "class".
Edit: not everything I said here is 100% true, there are some hacks in PHP that I did not mention; but I suspect they'll only make a HUGE mess out of your code.
Bookmarks