Im trying to modify a variable inside a function to be used outside.
The only way I know how to do this is to make the variable global like…
function sentence($Input) {
$Length = strlen($Input);
$end = substr($Input,-9);
if($Length < 20) {
echo "<p class='bg-danger'><span class='glyphicon glyphicon-remove pull-right' aria-hidden='true'></span>The Text you entered has to be at least 20 caracters, <small>It is ".$Length."</small></p>";
global $error;
$error = 1;
return false;
} else {
echo "<p class='bg-success'><span class='glyphicon glyphicon-ok pull-right' aria-hidden='true'></span>The last 9 characters of the sentence are ".$end."</p>";
return true;
then I use it in the page
if($error == 1) {
echo "<h3 class='text-danger'>You had at least 1 error</h3>";
echo "<a href='index.php'><span class='glyphicon glyphicon-repeat' aria-hidden='true'></span> Try Again</a>";
}
function sentence($Input) {
$Length = strlen($Input);
$end = substr($Input,-9);
if($Length < 20) {
echo "<p class='bg-danger'><span class='glyphicon glyphicon-remove pull-right' aria-hidden='true'></span>The Text you entered has to be at least 20 caracters, <small>It is ".$Length."</small></p>";
global $error;
$error = 1;
} else {
echo "<p class='bg-success'><span class='glyphicon glyphicon-ok pull-right' aria-hidden='true'></span>The last 9 characters of the sentence are ".$end."</p>";
$error = 0;
}
return $error;
}
Or keeping the function as is, returning a boolean:-
Another thing is, you could switch to using OOP in that matter because OOP would actually be helpful for you. And you won’t be using procedural anymore. People need to realize that OOP is NOT that hard to learn. If you are learning procedural, that’s already half way to OOP. You just need to take that other half of the step to actually learn it.
Take for example, we’ll use your snippet. You are probably calling it currently using.
echo my_function('Whatever is in here');
That’s basically the same thing in OOP. Here, try this one for size.
<?php
namespace Sitepoint;
class Sitepoint {
public function sentence($Input) {
$Length = strlen($Input);
$end = substr($Input,-9);
if($Length < 20) {
echo "<p class='bg-danger'><span class='glyphicon glyphicon-remove pull-right' aria-hidden='true'></span>The Text you entered has to be at least 20 caracters, <small>It is ".$Length."</small></p>";
return false;
} else {
echo "<p class='bg-success'><span class='glyphicon glyphicon-ok pull-right' aria-hidden='true'></span>The last 9 characters of the sentence are ".$end."</p>";
return true;
}
}
}
$input = 'Sitepoint';
$new = new Sitepoint();
$check = $new->sentence($input);
if($check == false) {
echo "<h3 class='text-danger'>You had at least 1 error</h3>";
echo "<a href='index.php'><span class='glyphicon glyphicon-repeat' aria-hidden='true'></span> Try Again</a>";
}