I was trying to make weather based PHP script to show weather related data.But,I'm facing this error message
Fatal error: Call to undefined method weather::get()
Would you please let me know how can i fix this or what was my problem??You can check out my code here:
<?php
include 'weather.php';
$t_weather = new weather();
$info = $t_weather->get('New York');
echo "Current temperature in {$info[0]['location']} is: {$info[0]['current_condition']['temperature']['f']} °F";
?>
This is weather.php:
<?php
class weather {
// API data
private $API_NAME = 'weather';
private $API_KEY = '***********';
}
?>
Thanks in advance.
Well your weather class doesn't have a method named get. Are you using someone else's class to do this? You should have something like:
class weather {
// API data
private $API_NAME = 'weather';
private $API_KEY = '***********';
public function get($location) {
// code that gets the weather for $location
}
}
Related
Confession:
I read many similar questions on this platform, but nothing seems closely aligned to my situation. Most of the questions seem to originate from binding params in prepared statements or execute statement.
In my case, the website runs smooth on a local server(Apache2). However, it throws the error below when published on live server.
Fatal error: Uncaught Error: Call to a member function signin() on boolean in /storage/ssd5/815/17670815/app/controllers/signin.php:16 Stack trace: #0 /storage/ssd5/815/17670815/app/core/app.php(33): Signin->index() #1 /storage/ssd5/815/17670815/public_html/index.php(4): App->__construct() #2 {main} thrown in /storage/ssd5/815/17670815/app/controllers/signin.php on line 16
Context
I'm using MVC (OOP) in PHP and here the relevant parts mentioned in the error. I hope this is not too much.
In the main index page, the line referred in the error is a core class(App) instantiation
<?php
session_start();
require_once '../app/initializer.php';
$app = new App(); //this is the line 4 mentioned in the error
In Signin controller class the line referred in the error is indicated below
<?php
class Signin extends Controller{
function index(){
//you can do this if passing data to view
$data["Page_title"] = "Signin";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// this is a debuggin code
//echo "I am signin controller <br />";
// show($_POST);
$user = $this->loadModel("User");
$user->signin($_POST); //this the line referred in the error
}
$this->view("zac/signin",$data);
}
}
In class APP the line is a callback - check below
<?php
class App {
private $controller = "home";
private $method = "index";
private $params = [];
public function __construct()
{
$url = $this->splitURL();
if(file_exists("../app/controllers/".strtolower($url[0]).".php")){
$this->controller = strtolower($url[0]);
//unset the array position
unset($url[0]);
}
require "../app/controllers/".$this->controller.".php";
// echo file_get_contents('http://smart-ecom.000webhostapp.com/app/controllers/'.$this->controller.".php");
//Create instance of whatever controller class is passed(if it exists, otherwise the home controller)
$this->controller = new $this->controller;
if(isset($url[1])){
if(method_exists($this->controller, $url[1])){
$this->method =$url[1];
unset($url[1]);
}
}
$this->params = array_values($url);
call_user_func_array([$this->controller, $this->method],$this->params); //this is line 33
}
/**
* splitURL gets url from browser and processes against the conroller classes and their methods
* #return array
*/
private function splitURL(){
//check if the the GET is set otherwise set the url to defualt class home
$url = isset($_GET['url']) ? $_GET['url'] :"home";
// return explode("/",filter_var(trim($_GET['url'],"/"), FILTER_SANITIZE_URL));
return explode("/",filter_var(trim($url,"/"), FILTER_SANITIZE_URL));
}
}
?>
The Database class's read function is as follows. This method isn't directly referred in the error message
public function read($query, $data = []){
$stmt = self::$conn->prepare($query);
$result = $stmt->execute($data);
if($result){
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(is_array($data) && count($data) > 0){
return $data;
}
}
return false;
}
As I mentioned earlier, this error fires on a live server but the website runs smooth in dev environment with PHP 7.4, Apache2, MySQL 8 Windows 10.
Your help is match appreciated in advance.
I learned this the hard way and I hope this can help someone with similar issues. The cause of the error because of how windows and Linux deals with case sensitivity in file names. In Windows, file names aren't case sensitive while in Linux - they are. So, that was the reason why the website was running smooth in the local dev environment(Windows machine) but throwing an error on a live server(which is Linux). To see the difference, refer to my earlier comment in this thread.
protected function loadModel($model){
if(file_exists("../app/models/". strtolower($model) . ".class.php")){
include "../app/models/".strtolower($model).".class.php";
return $model = new $model();
}else{
return false;
}
}
}
In the "include" line, you can see that I added the strtolower function to include the proper model and that solved the issue.
I have a project on PHP and I have to use a DOTNET DLL which was written on C# . I have to call different functions of the same object in two different PHP pages. In the first page it works but I get this error in the second page. Can you please help me? These are example ;
DOTNET DLL :
namespace FirstDotNet
{
[ComVisible(true)]
public class Class1
{
public string SampleFunction()
{
return "hello";
}
}
}
PHP Class File animals.php
class Animal{
var $abc;
public function do_it(){
$this->abc = new DOTNET("FirstDotNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxx", "FirstDotNet.Class1");
}
}
First PHP FILE a.php (this works, output is 'Hello')
require_once("animals.php");
session_start();
$first_animal = new Animal();
$_SESSION["animal"] = $first_animal;
$first_animal->do_it();
echo $first_animal->abc->SampleFunction();
Second PHP FILE b.php (this doesnt work, output is Fatal error: Call to undefined method dotnet::SampleFunction())
require_once("animals.php");
session_start();
$animal2 = $_SESSION["animal"];
echo $animal2->abc->SampleFunction();
I have a strange bug at the moment in my web service I am coding.
When I am loading an specific url I get a success and error at the same time?
This is what I have in my index.php:
<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "API Version not valid";
exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "Endpoint not valid";
exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
exit();
}
// load endpoint class and make an instance
try {
require_once($classFilePath);
$instance = new $endPoint($requestParts);
} catch (Exception $e) {
httpResponseCode(500);
echo $GLOBALS['http_response_code'];
exit();
}
and this is the corresponding "Tickets.php"
<?php
echo "OK";
?>
In the last two rows of my index.php, I am loading the specific class (named in the URL). For testing purposes, I have an "echo "OK" in this file. And this is the result when I am loading the URL I need:
http://api.medifaktor.de/v1/tickets
OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45
I get the OK I was expecting AND the error for the Class Tickets, that is not found. Line 45 is
$instance = new $endPoint($requestParts);
Can someone give me a helping hand?
Best
Sebastian
The problem is that you don't have a class "Tickets" defined. After you load the tickets.php file, you are attempting to instantiate a class. Loading a file is not the same thing as defining a class. Within tickets.php (or some other included file), you need to define the class, like so:
class Tickets
{
// some properties here
private $endpoint;
// some methods here
public function __construct($endpoint)
{
$this->endpoint = $endpoint;
}
}
If you're not sure how to construct classes in PHP, read the section in the manual on classes.
Update: I added some example code within the class for version PHP5+.
Try the following for your test, in the 'ticket.php' file add:
class Ticket {
public function __construct()
{
echo 'testing';
}
}
Then make sure you either namespace or require the file.
I'm getting this error when I run the script
php Fatal error: Cannot redeclare class AppMailCore in /appmail.core.php on line 10
I need to make loop that will also use some variables from a class file . The code from main.php looks like this :
$iesc = 1;
while($iesc less than 5)
{
include('includes/appmail.core.php');
---
I used "less than " in the code above 'cause I don't know to unescape "<" symbold within the pre markup .
I understand that I'm not allowed to re-delcare the class but I don't know how to make the class variables run through the loop .
appmail.core.php looks like this
require_once('appmail.config.php');
require_once('helpers'.DIRECTORY_SEPARATOR.'appmail.rest.php');
class AppMailCore
{
var $AppMailRest;
var $api_key;
var $url;
/**
* Initialises AppMailCore. Optionally provide runtime api key and url.
*/
function AppMailCore($api_key = APPMAIL_API_KEY, $url = APPMAIL_URL) {
$this->url = $url;
$this->api_key = $api_key;
$this->AppMailRest = new AppMailRest($this->url);
}
/**
* Asynchronously sends an email using Google App Engine
*
* Params are fairly self explanatory. However, note that the "from" address must be a registered email with
* your Google App Engine account.
*/
function send($to, $from, $subject, $plain, $html) {
$api_key = $this->api_key;
$status = $this->AppMailRest->post('send', compact('api_key','to','from','subject','plain','html'));
return $status;
}
}
the appmail.config.php loooks like this
$app1DB = new mysqli("localhost", "root", "", "ast");
$app1RSP = $app1DB->query("SELECT app_id FROM Application WHERE emails_sent fetch_assoc();
$app_id = $app1Object['app_id'];
define('APPMAIL_API_KEY', 'JLQ7P5SnTPq7AJvLnUysJmXSeXTrhgaJ');
define('APPMAIL_URL', "http://$app_id.appspot.com/");
$app1RSP->free();
$app1DB->close();
Basically I need to get variable APPMAIL_URL/$app_id in the class on each loop run.
Why aren't you doing the include before the loop ?
Another tip: use include_once ?
Third tip: include directly appmail.config.php if you need a constant from it, not appmail.core.php ?
EDIT
Basically I need to get variable
APPMAIL_URL/$app_id in the class on
each loop run.
If its value is supposed to change through the script execution (as I just saw), then you shouldn't define it as a constant.
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.