Global variables of function inside function of a class - function

class Someclass{
function topFunction()
{
function makeMeGlobal($var)
{
global $a, $b;
$a = "a".$var;
$b = "b".$var;
}
makeMeGlobal(1);
echo "$a <br>";
echo "$b <br>";
makeMeGlobal(2);
echo "$a <br>";
echo "$b <br>";
}
}
I am using that test code on codeigniter but nothings happen.
I suppose to print a result like this
a1
b1
a2
b2
How to handle those functions inside a class?

You declare globals inside function scope.
Try to declare them at class scope:
class Someclass{
function topFunction()
{
function makeMeGlobal($var)
{
global $a, $b;
$this->a = "a".$var;
$this->b = "b".$var;
}
makeMeGlobal(1);
echo $this->a . "<br>";
echo $this->b . " <br>";
makeMeGlobal(2);
echo $this->a . "<br>";
echo $this->b . "<br>";
}
}

you are creating the global variables inside the function, try creating them in the class scope rather than the function. that should work.

Related

.JSON file Retrieving Data - Look for a value and get related objects

<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
break;
}
}
return $country();
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
echo $country('$capital');
echo $country('$currency');
echo $country('$region');
?>
I followed this post - https://stackoverflow.com/a/38906191/3939981
If I rewrite the code inside function, it works
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
echo $capital;
echo $currency;
echo $region;
break;
}
}
return $currency;
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>
Maybe some parts of the code did not work..Any comments and thoughs
You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:
function getCountryInfo($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
return array(
"currency" => $country->currency[0],
"capital" => $country->capital,
"region" => $country->region
);
}
}
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");
echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";

Yii2 Optional textbox with Checkbox from database

I am using following code to generate checkboxes from database. I need to add optional textbox for some options. Can anybody give me clue to add it ?
$form->field($model_detail, 'DOCUMENT_TYPE_ID')
->checkboxList(
$listData,array('separator'=>'<BR />')
)->label('Select Document(s)');
You should extends ActiveField and write your custom checkboxList method. It may looks like this:
class ProjectActiveField extends ActiveField
{
/**
* #inheritdoc
*/
public function checkboxList($items, $options = [])
{
$inputs = '';
foreach ($items as $id => $value) {
$input = Html::activeCheckbox($this->model, $this->$id, $options);
$description = $options['itemDescriptions'][$id];
if ($description) {
$input = '<div class="checkbox">' . $description . $input . '</div>';
}
$inputs .= $input;
}
$this->adjustLabelFor($options);
$this->parts['{input}'] = $inputs;
return $this;
}
}

Zend error Connection

I have a problem with my code, the first code is like
<?php
require_once('zend/json.php');
require_once('zend/db.php');
//require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>'localhost',
'username'=>'stet',
'password'=>'test',
'dbname'=>'test'
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from info ";
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
and it works well, but I want to make it like
<?php
include ('table.php');
include ('config.php');
require_once('zend/json.php');
require_once('zend/db.php');
require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>$dbhost,
'username'=>$dbuser,
'password'=>$dbpass,
'dbname'=>$dbdb
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from ".$table;
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
I don't know whats wrong with this code, I need help.
the error message Notice: Undefined variable: dbdb in C:\wamp....
The config.php is only have code like $dbpass = 'test'; and like that, I'm creating a simple web and I want to make my code to other database and aplikasi, so I only changed the config.php and the table.php
for the table.php maybe will work if the config.php work.
Thanks.
You are using a class and not paying attention to variable scope.
I understand you have variables with values for the DB connection in that config.php file. Although these variables are available inside the script file with the include they are NOT available and accessible inside your class. The only difference would be any constants with define (or variables inside a global which is not a good idea).
You could create a config class inside the config.php and set the values as properties then instantiate that class inside your _koneksi method. And then you would use a require_once instead of the include.
UPDATE
So here's an example that is similar to your file where your include ('config.php'); is essentially the same as declaring your variables directly before the class begins.
// variable defined outside the class
$foo = 'foo';
class demo
{
public $bar = 'bar';
function test()
{
$foobar = 'foobar';
echo 'Class property $bar is:' . $this->bar . PHP_EOL;
echo 'Local variable $foobar is:' . $foobar . PHP_EOL;
}
function run()
{
if (isset($foo)) {
echo 'Global variable $foo is:' . $foo . PHP_EOL;
} else {
// This is where you have your problem.
// Variables from outside the class are not available.
echo 'Global variable $foo not found' . PHP_EOL;
}
}
}
$demo = new demo();
$demo->test(); // Class property $bar is:bar
// Local variable $foobar is:foobar
$demo->run(); // Global variable $foo not found
echo 'Variable $foo is: ' . $foo . PHP_EOL; // Class property $bar is:bar

Wordpress conditional display of page title inside the the_content using functions.php

Quick overview:
I am trying to get the page title to display inside the_content(), however this needs to be conditional, and only display if the page has an attached image. This also needs to be done through the functions file.
Where i've got up to:
This is the code i have so far... but it's not working, and i think the problem is that it's outside the loop... how can i work the code to lookup the page id... or how can i get it to work?
<?php
if ( has_post_thumbnail() ) {
add_filter('the_content', 'contentTitle');
function contentTitle($content='')
{
$theTitle = '<h1>' . get_the_title() . '</h1>';
return $theTitle . $content;
}
} else {
// Do nothing
}
?>
You should globalise the post object so that the post ID is available.
add_filter('the_content', 'contentTitle');
function contentTitle($content='')
{
global $post;
if( has_post_thumbnail( $post->ID ){
$theTitle = '<h1>' . get_the_title( $post->ID ) . '</h1>';
return $theTitle . $content;
}
}
SOLUTION
The "if" should have been inside the function itself.
<?php
add_filter('the_content', 'contentTitle');
function contentTitle($content='') {
if ( has_post_thumbnail() ) {
$theTitle = '<h1>' . get_the_title() . '</h1>';
return $theTitle . $content;
} else {
// Do nothing
}
}
?>

How to change a class variable in PHP?

I'm sure there is an easy answer to this question, but for the life of me, I can't find it. I'm using PHP5 and I'm trying to change the value of a class variable, but it doesn't appear to change. For example, I have something like this:
<?php
include_once "../includes/global.php";
loadDAOs('yweightGroups','yweightCourses','yweightUsers','user','yweightData');
class yweight {
private $header_includes;
private $user;
private $yweightUser;
//Description:
// Constructor.
//Parameters:
// -none-
//Returns:
// -nothing-
function __construct() {
global $r_action;
global $r_page;
$this->user = login_required();
if(!$this->user || empty($this->user)){
die();
goHome();
}
$this->header_includes = "";
if(isset($r_action)) {
$this->$r_action();
}
else if (isset($r_page)) {
$this->$r_page();
}
else {
$this->draw();
}
}
//Description:
// Draws the YWeight page
//Parameters:
// -none-
//Returns:
// -nothing-
function draw() {
global $r_page;
global $colorDAO;
global $yweightUsersDAO;
ob_start();
?>
<script type='text/javascript' src="./yweight.js"></script>
<link rel="stylesheet" type="text/css" href="yweight.css" />
<?php
$this->header_includes .= ob_get_clean();
$col = $colorDAO->read(17);
print_top("",$this->header_includes,"resources","",$col->value,$col->fontcolor);
$users = $yweightUsersDAO->GetByUserID($this->user->id);
if(!$users){
echo "<div class='msg_failed'>You are not authorized to view this page.</div>";
die();
}
$this->yweightUser = $users;
echo serialize($this->yweightUser[0]);
?>
<div id="yweight_area"></div>
<script type='text/javascript'>
<?php
if($users[0]->yweightUsers_intern == 0)
echo "drawPage('main_participant');";
else
echo "drawPage('main_intern');";
?>
</script>
<?php
print_bottom();
echo ob_get_clean();
}
//Description:
// Draws the main intern page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_intern() {
ob_start();
echo "hello intern";
echo ob_get_clean();
}
//Description:
// Draws the main participant page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_participant() {
global $yweightDataDAO;
ob_start();
$this->yweightUser = $this->yweightUser[0];
echo serialize($this->yweightUser);
?>
<div id="banner_div">
<img class="banner" width="927" src="images/ParticipantsMain.jpg" />
<img id="tracker_btn" class="std_btn" src="images/trackerButton.png" />
<img id="summary_btn" class="std_btn" src="images/summaryButton.png" />
<img id="requirements_btn" class="std_btn" src="images/reqButton.png" />
</div>
<div id="discussion_board_input_div">
<textarea id="discussion_board_input" />
<?php
echo build_btn("green",100,25,"Submit","","","","",
'submit_post()',"margin-top:5px; margin-bottom:5px; float:right;");
?>
<div class="clear_floats" />
</div>
<div id="discussion_board_div">
</div>
<?php
echo ob_get_clean();
}
function submit_post(){
global $yweightDataDAO;
global $userDAO;
global $r_post;
echo serialize($this->yweightUser);
$userDataID = $yweightDataDAO->GetByUserID($this->yweightUser->user_id);
if($userDataID){
$userData = $yweightDataDAO->read($userDataID);
$userDiscussion = unserialize($userData->yweightData_discussionBoard);
}
$userDiscussion[$this->user->firstName . time()] = $r_post;
$userData->yweightData_discussionBoard = serialize($userDiscussion);
$yweightDataDAO->save($userData);
}
}
$recs = new yweight();
?>
submit_post() is an ajax called function. The error I'm getting is that it says $this->yweightUser is undefined. I didn't orignally include all of the code because I thought that I was just misunderstanding how class variables are declared.
You have a typo. Use __construct. Two (_ _) underscores. Your fooVariable is never getting set. After it gets set it works fine.
Update: You only set $this->yweightUser in your function draw() method. If you don't call draw() before ajax_post() or w/e, it will not be defined.
As mentioned above, fix the syntax errrors and it works, 2 underscores for the constructor and opening brace for the constructor and also brackets for arguments:
class foo {
protected $fooVariable;
function __construct () {
$this->fooVariable = "hello world";
$this->changeVariable();
}
function changeVariable(){
$this->fooVariable = "goodbye world";
$this->echoVariable();
}
function echoVariable(){
echo $this->fooVariable;
}
}
$foo = new foo();