How to override a variable in PHP that's in two functions - php

function d20() {
$rollAll = false;
$roll = rand(1,20);
if ($rollAll == false) {
echo $roll;
}
}
function rollAll() {
$rollAll = true;
d20();
}
rollAll();
I want to make it so that whenever I call the rollAll function, $rollAll will be true and it won't echo the roll. Sorry if this problem seems really stupid, but I'm new to PHP.
Thanks.

#Rizier123 Answered just i pass the variable from rollAll to d20
function d20($rollAll) {
$roll = rand(1,20);
if ($rollAll == false) {
echo $roll;
}
}
function rollAll() {
$rollAll = true;
d20($rollAll );
}
rollAll();

set the variable $rollAll in global scope or pass as function params
function d20($rollAll) {
$rollAll = false;
$roll = rand(1,20);
if ($rollAll == false) {
echo $roll;
}
}
function rollAll() {
$rollAll = true;
d20( $rollAll );
}
rollAll();
or
$rollAll = true;// or false
function d20() {
$rollAll = false;
$roll = rand(1,20);
if ($rollAll == false) {
echo $roll;
}
}
function rollAll() {
$rollAll = true;
d20( );
}
rollAll();

Related

Convert this specific mysql bd class to mysqli

Can you please help me to fully convert this class to work with mysqli?
It's a class working on an old system, I just want to make it work with mysqli without having to modify the existing code on all the system.
I tried but with no success.
Thanks in advance!
class BD {
var $sServidor = "host";
var $sBaseDeDatos = "DB";
var $sUsuario = "user";
var $sClave = "pass";
function Conectar() {
if (($this->sServidor != "") && ($this->sUsuario != "")) {
$this->oConexion = mysql_connect($this->sServidor, $this->sUsuario, $this->sClave);
mysql_select_db($this->sBaseDeDatos, $this->oConexion);
mysql_set_charset("utf8", $this->oConexion);
}
}
function RetornarConexion() {
return $this->oConexion;
}
function Seleccionar($pSQL, $pRetornarFila = false) {
$oResultado = $this->Ejecutar($pSQL);
return (($pRetornarFila) ? $this->RetornarFila($oResultado) : $oResultado);
}
function RetornarFila($pResultado) {
return mysql_fetch_array($pResultado);
}
function ContarFilas($pResultado) {
$lFilas = 0;
if ($pResultado) {
$lFilas = mysql_num_rows($pResultado);
}
return $lFilas;
}
function Ejecutar($pSQL) {
$this->Conectar();
$oResultado = mysql_query($pSQL, $this->oConexion);
if ($oResultado) {
if (strpos(strtoupper($pSQL), "INSERT INTO") !== false) {
$oResultado = mysql_insert_id();
} else if (strpos(strtoupper($pSQL), "UPDATE") !== false) {
$oResultado = mysql_affected_rows();
}
}
return $oResultado;
}
function RetornarTipo($pResultado, $pCampo) {
$sTipo = "";
if ($pResultado) {
$sTipo = mysql_field_type($pResultado, $pCampo);
}
return $sTipo;
}
function RetornarLongitud($pResultado, $pCampo) {
$lLongitud = 0;
if ($pResultado) {
$lLongitud = mysql_field_len($pResultado, $pCampo);
}
return $lLongitud;
}
function Desconectar() {
mysql_close($this->oConexion);
}
}
Okay I'm testing it and think it works okay. Here's the code:
P / D: Sorry for wasting your time. Conclusion: I have to sleep a few more hours per day. Thanks and sorry again.
class BD {
var $sServidor = "host";
var $sBaseDeDatos = "DB";
var $sUsuario = "user";
var $sClave = "pass";
function Conectar() {
if (($this->sServidor != "") && ($this->sUsuario != "")) {
$this->oConexion = mysqli_connect($this->sServidor, $this->sUsuario, $this->sClave);
mysqli_select_db($this->oConexion, $this->sBaseDeDatos);
mysqli_set_charset($this->oConexion, "utf8");
}
}
function RetornarConexion() {
return $this->oConexion;
}
function Seleccionar($pSQL, $pRetornarFila = false) {
$oResultado = $this->Ejecutar($pSQL);
return (($pRetornarFila) ? $this->RetornarFila($oResultado) : $oResultado);
}
function RetornarFila($pResultado) {
return mysqli_fetch_array($pResultado);
}
function ContarFilas($pResultado) {
$lFilas = 0;
if ($pResultado) {
$lFilas = mysqli_num_rows($pResultado);
}
return $lFilas;
}
function Ejecutar($pSQL) {
$this->Conectar();
$oResultado = mysqli_query($this->oConexion, $pSQL);
if ($oResultado) {
if (strpos(strtoupper($pSQL), "INSERT INTO") !== false) {
$oResultado = mysqli_insert_id($this->oConexion);
} else if (strpos(strtoupper($pSQL), "UPDATE") !== false) {
$oResultado = mysqli_affected_rows($this->oConexion);
}
}
return $oResultado;
}
function RetornarTipo($pResultado, $pCampo) {
$sTipo = "";
if ($pResultado) {
$sTipo = mysqli_field_type($pResultado, $pCampo);
}
return $sTipo;
}
function RetornarLongitud($pResultado, $pCampo) {
$lLongitud = 0;
if ($pResultado) {
$lLongitud = mysqli_field_len($pResultado, $pCampo);
}
return $lLongitud;
}
function Desconectar() {
mysqli_close($this->oConexion);
}
}

Disable radio button based on PHP function

I want to call the javascript function based on the result coming from a PHP script.
if ($verify == 'Y' and $approve== 'Y' and $approve_2=='Y') {
$state = "disable";
} else {
$state = "undisable";
}
Below is my javascript function
function disable() {
document.getElementById("approvedd1").disabled = true;
document.getElementById("approvedd2").disabled = true;
}
function undisable() {
document.getElementById("approvedd1").disabled = false;
document.getElementById("approvedd2").disabled = false;
}
document.onreadystatechange = <?php echo $state; ?>()
This does not work.
I want to call function that can disable radio button, when the page has loaded.
The current output of your java script will be
function disable() {
document.getElementById("approvedd1").disabled = true;
document.getElementById("approvedd2").disabled = true;
}
function undisable() {
document.getElementById("approvedd1").disabled = false;
document.getElementById("approvedd2").disabled = false;
}
document.onreadystatechange = disabled/undisabled()
better you can try
php
if ($verify == 'Y' and $approve== 'Y' and $approve_2=='Y') {
$state = "true";
} else {
$state = "false";
}
Java Script
document.onreadystatechange = MyFun() {
document.getElementById("approvedd1").disabled = <?php echo $state; ?>;
document.getElementById("approvedd2").disabled = <?php echo $state; ?>;
}

Argument 1 passed to something::__construct must be

i am working on an addon, but i got a problem
[22:03:08] [CRITICAL]: "Could not pass event 'pocketmine\event\player\PlayerInteractEvent' to 'MTeamPvP v1.0.0 Beta': Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined on MCrafters\TeamPvP\TeamPvP
[22:03:08] [NOTICE]: InvalidArgumentException: "Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined" (E_RECOVERABLE_ERROR) in "/DevTools/src/MCrafters/TeamPvP/GameManager" at line 13
also sorry for the different error broadcasting
code : (please don't care about the other classes except GameManager and TeamPvP)
TeamPvP.php:
<?php
namespace MCrafters\TeamPvP;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat as Color;
use pocketmine\utils\Config;
use pocketmine\event\Listener;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\player\PlayerDeathEvent;
use pocketmine\math\Vector3;
use pocketmine\level\Position;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\Player;
use pocketmine\block\Block;
use pocketmine\item\Item;
use pocketmine\block\WallSign;
use pocketmine\block\PostSign;
use pocketmine\scheduler\ServerScheduler;
class TeamPvP extends PluginBase implements Listener
{
// Teams
public $reds = [];
public $blues = [];
public $gameStarted = false;
public $yml;
public function onEnable()
{
// Initializing config files
$this->saveResource("config.yml");
$yml = new Config($this->getDataFolder() . "config.yml", Config::YAML);
$this->yml = $yml->getAll();
$this->getLogger()->debug("Config files have been saved!");
$this->getServer()->getScheduler()->scheduleRepeatingTask(new Tasks\SignUpdaterTask($this), 15);
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->getServer()->getLogger()->info(Color::BOLD . Color::GOLD . "M" . Color::AQUA . "TeamPvP " . Color::GREEN . "Enabled" . Color::RED . "!");
}
public function isFriend($p1, $p2)
{
if ($this->getTeam($p1) === $this->getTeam($p2) && $this->getTeam($p1) !== false) {
return true;
} else {
return false;
}
}
// isFriend
public function getTeam($p)
{
if (in_array($p, $this->reds)) {
return "red";
} elseif (in_array($p, $this->blues)) {
return "blue";
} else {
return false;
}
}
public function setTeam($p, $team)
{
if (strtolower($team) === "red") {
if (count($this->reds) < 5) {
if ($this->getTeam($p) === "blue") {
unset($this->blues[array_search($p, $this->blues)]);
}
array_push($this->reds, $p);
$this->getServer()->getPlayer($p)->setNameTag("§c§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->blues) < 5) {
$this->setTeam($p, "blue");
} else {
return false;
}
} elseif (strtolower($team) === "blue") {
if (count($this->blues) < 5) {
if ($this->getTeam($p) === "red") {
unset($this->reds[array_search($p, $this->reds)]);
}
array_push($this->blues, $p);
$this->getServer()->getPlayer($p)->setNameTag("§b§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->reds) < 5) {
$this->setTeam($p, "red");
} else {
return false;
}
}
}
public function removeFromTeam($p, $team)
{
if (strtolower($team) == "red") {
unset($this->reds[array_search($p, $this->reds)]);
return true;
} elseif (strtolower($team) == "blue") {
unset($this->blues[array_search($p, $this->blues)]);
return true;
}
}
public function onInteract(PlayerInteractEvent $event)
{
$p = $event->getPlayer();
$teams = array("red", "blue");
if ($event->getBlock()->getX() === $this->yml["sign_join_x"] && $event->getBlock()->getY() === $this->yml["sign_join_y"] && $event->getBlock()->getZ() === $this->yml["sign_join_z"]) {
if (count($this->blues) < 5 && count($this->reds) < 5) {
$this->setTeam($p->getName(), $teams[array_rand($teams, 1)]);
$s = new GameManager();
$s->run();
} else {
$p->sendMessage($this->yml["teams_are_full_message"]);
}
}
}
public function onEntityDamage(EntityDamageEvent $event)
{
if ($event instanceof EntityDamageByEntityEvent) {
if ($event->getEntity() instanceof Player) {
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName()) && $this->gameStarted == true) {
$event->setCancelled(true);
$event->getDamager()->sendMessage(str_replace("{player}", $event->getPlayer()->getName(), $this->yml["hit_same_team_message"]));
}
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName())) {
$event->setCancelled(true);
}
}
}
}
public function onDeath(PlayerDeathEvent $event)
{
if ($this->getTeam($event->getEntity()->getName()) == "red" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "red");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
} elseif ($this->getTeam($event->getEntity()->getName()) == "blue" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "blue");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
foreach ($this->blues as $b) {
foreach ($this->reds as $r) {
if (count($this->reds) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($b)->getInventory()->clearAll();
$this->removeFromTeam($b, "blue");
$this->getServer()->getPlayer($b)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
$this->getServer()->broadcastMessage("Blue Team won TeamPvP!");
} elseif (count($this->blues) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($r)->getInventory()->clearAll();
$this->removeFromTeam($r, "red");
$this->getServer()->getPlayer($r)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
}
}
}
}//class
GameManager.php :
<?php
namespace MCrafters\TeamPvP;
use pocketmine\scheduler\ServerScheduler as Tasks;
class GameManager
{
public $reds;
public $blues;
public $gst;
public $gwt;
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
public function run()
{
$this->reds = $this->plugin->reds;
$this->blues = $this->plugin->blues;
if (count($this->reds) < 5 && count($this->blues) < 5) {
$this->gst = Tasks::scheduleRepeatingTask(new Tasks\GameStartTask($this), 20)->getTaskId();
Tasks::cancelTask($this->gwt);
} else {
$this->gwt = Tasks::scheduleRepeatingTask(new Tasks\GameWaitingTask($this), 15)->getTaskId();
}
}
}
namespace correct, class and file name correct, and all other functions from other classes have nothing to do with this :) check the line where there is GameManager::run() in TeamPvP class.
i already know there is one about this, but i didn't understand it.
Thank You for your help.
You have a type hint
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
So when you go to instantiate MCrafters\TeamPvP\GameManager you have to pass it an instance of \MCrafters\TeamPvP\TeamPvP
$team = new \MCrafters\TeamPvP\TeamPvP();
$manager = new \MCrafters\TeamPvP\GameManager($team)

Why does this PHP function cycle endlessly?

function nonrecgen($min, $max, $amount) {
for($i=0;$i<$amount;$i++) {
$NrArray[$i] = rand($min,$max);
echo $NrArray[$i];
do {
for($j=0;$j<=$i;$j++) {
if ($NrArray[$j] == $NrArray[$i]) {
$NrArray[$i] = rand($min,$max); }
}
$Reccuring = false;
if ($i > 0) {
for($k=0;$k<=$i;$k++) {
if ($NrArray[$k] == $NrArray[$i]) {
$Reccuring = true; }
}
}
}
while ($Reccuring = true);
}
Return $NrArray;
}
$Test = nonrecgen(0,1,2);
print_r($Test);
I wanted to look into how to generate an array of nonreccuring numbers and while this is certainly not the most efficient way I believe, I can't seem to figure out why it loops endlessly on the first iteration. I tried logical analysis over and over, but there has to be something I'm missing.
do {
...
} while ($Reccuring = true);
Because your while statement sets $Reccuring to true, instead of evaluating it.
Try:
do {
...
} while ($Reccuring === true);
Other than the = to == you were also resetting the $Recurring in the wrong place:
<?
function nonrecgen($min, $max, $amount)
{
for($i=0;$i<$amount;$i++)
{
$NrArray[$i] = rand($min,$max);
do
{
for($j=0;$j<=$i;$j++)
{
if ($NrArray[$j] == $NrArray[$i])
{
$NrArray[$i] = rand($min,$max);
}
}
if ($i > 0)
{
for($k=0;$k<=$i;$k++)
{
if ($NrArray[$k] == $NrArray[$i])
{
$Reccuring = true;
}
}
}
$Reccuring = false;
}
while ($Reccuring == true);
}
return $NrArray;
}
$Test = nonrecgen(0,2,5);
echo "<pre>";
print_r($Test);
?>
You're currently assigning a value rather than checking (which will always be true).
Change it to: while ($Reccuring == true);

pass value from embedded function into conditional of page the embedded function is included on

I have a page that includes/embeds a file that contains a number of functions.
One of the functions has a variable I want to pass back onto the page that the file is embedded on.
<?php
include('functions.php');
userInGroup();
if($user_in_group) {
print 'user is in group';
} else {
print 'user is not in group';
}
?>
function within functions.php
<?php
function userInGroup() {
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
}
}?>
I am unsure as to how I can pass the value from the function userInGroup back to the page it runs the conditional if($user_in_group) on
Any help is appreciated.
Update:
I am userInGroup(array("STAFF","STUDENTS","FACULTY"));
which then is
<?php
function userInGroup($group_access) {
session_start();
if(isset($_SESSION['user_session'])) {
$username = $_SESSION['user_session'];
$group_session = $_SESSION['group_session'];
$user_full_name = $_SESSION['user_full_name'];
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
} return $user_in_group;
} else {
print 'not logged in';
}
?>
Easiest way:
$user_in_group = userInGroup();
function userInGroup() {
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group == FALSE;
}
}
return $user_in_group;
}
Use the return statement.
You can use your original function with one minor modification:
<?php
function userInGroup() {
**global $user_in_group;**
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
}
}?>

Categories