I have a static variable like so to keep track of some operations in memory without using a real database
<?php
class Database
{
public static $database = array();
}
When I try to access the database from another php file like so
<?php
include 'database.php';
function createPaymentRef($username, $password, $amount)
{
$finalResult = array();
$ref = generateTimedTransactionRef($username, $password, $amount);
global $requestData;
global $ip;
Database::$database->unset($username); //Expected type 'object'. Found 'array'.intelephense(1006) error
$requestData->ip = $ip;
$requestData->reference = $ref;
$finalResult['result'] = $ref;
return $finalResult;
}
?>
I am get an error saying
Expected type 'object'. Found 'array'.intelephense(1006)
How can I resolve this?
-> is used to access properties or methods of an object. Database::$database is an array, not an object. The syntax to unset an array element is
unset($array[$index])
so it should be
unset(Database:$database[$username]);
Check if the static variable exists and if the array element in it exists, then unset using unset(Database::$database[$username]):
$db = Database::$database;
if($username && $db && isset($db[$username])){
unset(Database::$database[$username]);
}
Related
as far as I can tell the function is only declared once . but I get this error Cannot redeclare calcPercentages() and it tells me it was declared on line 17 which is correct
the function that contains the errant function...
function auditStats($audit){
$mysqli = dbConnect();
$audit_id = $audit;
$result = $mysqli->query("SELECT imageGrade, SUM(imageGrade=1) AS grade1, SUM(imageGrade=2) AS grade2, SUM(imageGrade=3) AS grade3, COUNT(*) AS total_imgs FROM image WHERE type != 'standard' and auditID ='$audit_id'")or exit("Error code ({$mysqli->errno}): {$mysqli->error}");
$row = $result->fetch_assoc();
$grade1 = $row['grade1'];
$grade2 = $row['grade2'];
$grade3 = $row['grade3'];
$totalImgs = $row['total_imgs'];
function calcPercentages($grade, $total){
$percent = round(($grade / $total) * 100,2);
return $percent;
}
if ($totalImgs != 0){
$percent_1 = calcPercentages($grade1, $totalImgs);
}
$return_array = [
'total'=>$totalImgs,
'percent_1'=>$percent_1
];
return $return_array;
}
The function isn't being called anywhere except within the auditStats function and the results are called further down the page using
$percent_1 = auditStats($auditID)[percent_1];
Please excuse me if I have made on obvious newbie error, I am moving from procedural to OOP and am just starting out with it.
You declare calcPercentages inside the auditStats function, so it gets re-declared every time you call auditStats.
Move calcPercentages outside of auditStats.
In PHP, unlike say JS, a function is never local to another function, so when the line function calcPercentages... is reached, you're creating a global function called calcPercentages. When it's run again, you're trying to create another global function with the same name, and you get the error.
Either move the declaration outside globally, put it in a class or object or make an anonymous function.
I will be straight to the point with this. Can't seem to find it anywhere on the internet. Maybe it is not even possible, i dont know. I do really like to use the method "divide and rule", created it myself. Splitting as much files as possible for easy management (small files and such).
But here is my problem:
I have 5 files:
index.php
inc/config.php
inc/Database.class.php
inc/sidebar.php
inc/forms.php
Okay, what i have done is this:
in my config.php file i included the Database.class.php file and created an object.
include 'Database.class.php';
$user = "root";
$pass = "";
$host = "localhost";
$database = "blah blah";
$db = new Database($user, $pass, $host, $database);
$db->connect();
So i included this config.php and sidebar.php in my index.php file.
(shortened the code, but it functions the same)
include 'inc/config.php';
include 'inc/sidebar.php';
In my sidebar i have a form, for users to login.
in sidebar.php i just include forms.php, this is the forms.php:
(I used print_r to debug my file, to see if anything returns and i left out the method loginFormShow because it is very long and not relevant)
function loginFormProcess($user, $pass)
{
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
if (!isset($_POST['submit'])) {
loginFormShow();
} else {
if ($_POST['user'] == "")
{
loginFormShow(1);
}
else if ($_POST['pass'] == "")
{
loginFormShow(2);
}
else
{
$user = $_POST['user'];
$pass = $_POST['pass'];
loginFormProcess($user, $pass);
}
}
And thus, what the problem is. When i try to call the function loginFormProcess, it cant use the object $db.
Can i use 1 object for this? Because on the index page i am going to require some other data from the database. Do i need to create an object for the index page and one for the login form?
Is there any other solution?
If i am not clear, i would love to give some more explanation.
Cheers,
Clemenz
The best solution would be to pass the database object to the function's arguments as follows:
function loginFormProcess($user, $pass, Database $db) {
And call it with an appropriate Database object. This is what know as dependency-injection.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
For reference: http://php.net/manual/en/language.variables.scope.php
You need to declare $db as global.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
See: http://www.php.net/manual/en/language.variables.scope.php
The variable $db is created as a global variable in your config.php file. This is invisible from inside the loginFormProcess function. A shotcut solution you can use is declaring your intention of using a global variable by adding the statement global $db; as the first statement inside your function
I want to validate a form with php.
Therefor I created a class "benutzer" and a public function "benutzerEintragen" of this class to validate the form:
class benutzer
{
private $username = "";
private $mail = "";
private $mail_check = "";
private $passwort = "";
private $passwort_check = "";
public $error_blank = array();
public $error_notSelected = array();
public $error_notEqual = array();
public function benutzerEintragen () {
$textfields[0] = $this->username;
$textfields[1] = $this->mail;
$textfields[2] = $this->mail_check;
$textfields[3] = $this->passwort;
$textfields[4] = $this->passwort_check;
foreach ($textfields as $string) {
$result = checkFormular::emptyVariable($string);
$error_blank[] = $result;
}
In the function "benutzerEintragen" i filled the variables "username,mail" and so on with the appropriate $_POST entries (not shown in the code above). The call
checkFormular::emptyVariable($string)
just returns "TRUE" if the field is not set or empty otherwise FALSE.
Now when i try to create a new instance of this class, execute the function and get access to $error_blank[0] the array is empty!
if (($_SERVER['REQUEST_METHOD'] == 'POST')){
$BENUTZER = new benutzer();
$BENUTZER->benutzerEintragen();
echo $BENUTZER->error_blank[0];}
So the last line is leading to a "Notice: Undefined offset: 0". It seems to be related to the array structure, because if i do
echo $BENUTZER->mail;
I get any input I wrote in the form, which is correct. Also the foreach loop seems to do the right thing when i run the debugger in phpEd, but it seems like the array "error_blank" is erased after the function is executed.
Any help would be greatly appreciated. Thanks in advance.
There is a scope problem here. You do have a class attribute with the name. Unlike in Java where using a local variable with the same name as a class variable automatically selects the class attribute this is not the case in PHP.
Basically you are saving your output in a local variable which gets discarded once you leave the function. Change $error_blank[] = $result; to $this->error_blank[] = $result; and you should be fine.
First of all this seems overly complicated way to do a simple task, but that wasn't actually the question.
You are creating a new $error_blank variable that is only in function scope. If you wish to use the class variable you should use $this->error_blank[]
I am trying to assign a variable to a class in PHP, however I am not getting any results?
Can anyone offer any assistance? The code is provided below. I am trying to echo the URL as shown below, by first assigning it to a class variable.
class PageClass {
var $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
$page->get_absolute_path(); //this should echo the URL as defined above - but does not
It also works for me.
Take a look at a live example of your code here.
However, there are a few things you should change about your class.
First, Garvey does make a good point that you should not be using var. That's the older PHP4, less OOP conscious version. Rather declare each variable public or private. In fact, you should declare each function public or private too.
Generally, most classes have private variables, since you usually only want to change the variables in specific ways. To achieve this control you usually set several public methods to allow client functions to interact with your class only in restricted predetermined ways.
If you have a getter, you'd probably want a setter, since these are usually used with private variables, like I described above.
A final note is that functions named get usually return a value. If you want to display a value, it is customary to use a name like display_path or show_path:
<?php
class PageClass
{
private $absolute_path = NULL;
public function set_absolute_path($path)
{
$this->absolute_path = $path;
}
public function display_absolute_path()
{
echo $this->absolute_path;
}
}
$page = new PageClass();
$page->set_absolute_path("http://localhost:8888/smile2/organic/");
$page->display_absolute_path();
// The above outputs: http://localhost:8888/smile2/organic/
// Your variable is now safe from meddling.
// This:
// echo $this->absolute_path;
// Will not work. It will create an error like:
// Fatal error: Cannot access private property PageClass::$absolute_path on ...
?>
Live Example Here
There's a section on classes and objects in the online PHP reference.
class PageClass {
public $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
return $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo $page->get_absolute_path();
Works fine for me.
Have you checked that the script and esp. the code in question is executed at all?
E.g. add some unconditional debug-output to the script. Or install a debugger like XDebug to step through the code and inspect variables.
<?php
class PageClass {
var $absolute_path = NULL; // old php4 declaration, see http://docs.php.net/oop5
function get_absolute_path() { // again old php4 declaration
$url = $this->absolute_path;
echo "debug: "; var_dump($url);
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo "debug: page->get_absolute_path\n";
$page->get_absolute_path();
I'm trying to create a PHP function that adds an event to a google Calendar. It appears to be building the object correctly but it throws a "Call to a member function getDOM() on a non-object in FeedEntryParent.php" error when trying to add the event. Here is the abbreviated class with only the constructor and the function that adds the event:
class GCal_datasource {
private $user = 'xxxxxxx';
private $pass = 'xxxxxxxxx';
private $client;
private $gdata_cal;
private $calendar;
private $visibility;
public function __construct($settings = NULL){
session_start();
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_HttpClient');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
if($settings == NULL){
$settings = array();
$settings['calendar'] = 'default';
$settings['visibility'] = 'full';
}
$this->calendar = $settings['calendar'];
$this->visibility = $settings['visibility'];
$this->client = $this->get_ClientLoginHttpClient();
$this->gdata_cal = new Zend_Gdata_Calendar($this->client);
}
public function create_event($fields){
$gc = $this->gdata_cal;
$new_event = $this->gdata_cal->newEventEntry();
echo '<pre>';
print_r($fields);
echo '</pre>';
if(isset($fields['quick_add'])){
$new_event->content = $gc->newContent($fields['quick_add']);
$new_event->quickAdd = $gc->newQuickAdd(true);
} else if (isset($fields['title']) && isset($fields['when'])) {
$new_event->title = $fields['title'];
$where = $gc->newWhere($fields['where']);
$new_event->where = array($where);
$desc = $gc->newContent($fields['desc']);
$new_event->content = $desc;
$new_event->content->type = 'text';
$new_event->when = self::build_when_array($fields['when']);
if(isset($fields['web_content'])){
$new_event->link = web_event_array($fields['web_content']);
}
}
echo '<pre>';
print_r($new_event);
echo '</pre>';
$gc->insertEvent($new_event);
return $created_event->id->text;
}
}
The error (I believe) is how I am calling insertEvent() towards the end of the code. The only reason I think that is I only get the error when it exists and if I remove it the echo above it prints out the Event object as intended.
Anyone with a better grasp of the Goggle PHP API that can lend me a hand I would greatly appreciate.
I had this problem.
I think you have to change string
$new_event->title = $fields['title'];
to
$new_event->title = $service->newTitle($fields['title']);
Call to a member function getDOM() on a non-object in FeedEntryParent.php means that somewhere in the file named "FeedEntryParent.php" you have called getDOM() on a variable and that variable is not an object and so does not have a getDOM() method.
Nowhere in the code you posted is a call to getDOM(), so the error is not generated in the posted code.
Track down that call to getDOM(). The error usually gives you a line number. See what variable you are calling the method on. That variable is not an object. Find where that variable is set - that's probably where your problem is.