I created a class and try to call in a method, but however in my error log, I am getting response "Uncaught Error: Call to undefined method Customersss::throwError()", please what am I doing wrong, because I know I have created throwError(), I can't seem to be able to access the class.
Firstly the class trying to call object
$this->throwError(INVALID_DATA_TTT, "Invalid shipping fee"); //WHERE I SUSPECT ERROR IS BEING GENERATED
The full error
PHP Fatal error: Uncaught Error: Call to undefined method
Customersss::throwError() in
/home/osconliz/public_html/Osconlizapicall/customers.php:276 Stack
trace:
#0 /home/osconliz/public_html/Osconlizapicall/api.php(177): Customersss->insertNewDelivery()
#1 [internal function]: Api->create_insert_new_delivery()
#2 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#3 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#4 {main} thrown in /home/osconliz/public_html/Osconlizapicall/customers.php on line 276
customers.php
require_once('constants.php');
require_once('rest.php');
class Customersss {
private $id;
private $shipping_fee;
private $pickup_fee;
function setId($id){ $this->id = $id; }
function getId() { return $this->id; }
function setShipping_fee($shipping_fee){ $this->shipping_fee = $shipping_fee; }
function getShipping_fee() { return $this->shipping_fee; }
function setPickup_fee($pickup_fee){ $this->pickup_fee = $pickup_fee; }
function getPickup_fee() { return $this->pickup_fee; }
public function __construct(){
$db = new DbConnect();
$this->dbConn = $db->connect();
}
public function insertNewDelivery(){
if ($this->shipping_fee == ""){
$this->throwError(EMPTY_PARAMETER, "Empty shipping fee");
exit();
}
if ($this->shipping_fee == ""){
$this->throwError(INVALID_DATA_TTT, "Invalid shipping fee");
exit();
}
}
}
rest.php
require_once('constants.php');
class Rest {
protected $request;
protected $serviceName;
protected $param;
public function processApi(){
$api = new API;
$rMethod = new reflectionMethod('API', $this->serviceName);
if(!method_exists($api, $this->serviceName)){
$this->throwError(API_DOST_NOT_EXIST, "API does not exist");
}
$rMethod->invoke($api);
}
public function throwError($code, $message){
header("content-type: application/json");
$errorMsg = json_encode(['error' => ['status'=>$code, 'message'=>$message]]);
echo $errorMsg; exit;
}
}
constants.php
define('INVALID_DATA_TTT', 350);
define('EMPTY_PARAMETER', 404);
define('API_DOST_NOT_EXIST', 400);
define('ACCESS_TOKEN_ERRORS', 500);
api.php
require_once "customers.php";
require_once "constants.php";
class Api extends Rest {
public $dbConn;
public function __construct(){
parent::__construct();
$db = new DbConnect;
$this->dbConn = $db->connect();
}
public function create_insert_new_delivery(){
$shipping_fee= $this->validateParameter('item_category', $this->param['shipping_fee'], STRING, true);
try {
$cust = new Customersss;
} catch (Exception $e){
$this->throwError(ACCESS_TOKEN_ERRORS, $e->getMessage());
}
}
You are calling Rest::ThrowError() from Customersss class. It means your function is unreachable in this context.
To call this Rest method from the Customersss class, you can:
extend Rest to Customersss (see inheritance)
make ThrowError() a static method (see static)
Using inheritance:
class Customersss extends Rest { /* your properties/methods */ }
Using a static method:
class Rest {
static public function throwError($code, $message){ /* your code */ }
}
Callable with Rest::ThrowError()
Related
i dont really understand why i get this Error Message and i hope you guys can help:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Controller\Home::__construct(), 0 passed in /mnt/c/mvc/index.php on line 25 and exactly 1 expected in /mnt/c/mvc/src/Controller/Home.php:12 Stack trace: #0 /mnt/c/mvc/index.php(25): App\Controlyler\Home->__construct() #1 {main} thrown in /mnt/c/mvc/src/Controller/Home.php on line 12
index.php
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
use App\Core\{Router, Request};
use App\Service\View;
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/src/Core/Bootstrap.php';
$routerLoad = Router::load('src/core/Routes.php')
->direct(Request::uri());
$routerAction = new $routerLoad;
$routerAction->action();
$view = new View();
$view->display();
Home.php
namespace App\Controller;
use App\Service\ViewInterface;
use App\Service\View;
class Home implements Controller
{
private ViewInterface $view;
public function __construct(View $view)
{
$this->view = $view;
}
public function action(): void
{
$this->view->addTemplate('layout.tpl');
$this->view->addTlpParam('headline', 'Home');
$this->view->addTlpParam('info', 'Welcome');
$this->view->addTlpParam('name', 'User');
$this->view->display();
}
}
View.php
namespace App\Service;
class View implements ViewInterface
{
private \Smarty $smarty;
private string $template;
public function __construct()
{
$this->smarty = new \Smarty();
$this->smarty->setTemplateDir('/mnt/c/mvc/src/View/templates');
$this->smarty->setCompileDir('/mnt/c/mvc/src/smarty/templates_c');
$this->smarty->setCacheDir('/mnt/c/mvc/src/smarty/cache');
$this->smarty->setConfigDir('/mnt/c/mvc/src/smarty/configs');
}
public function addTemplate(string $template):void
{
$this->template = $template;
}
public function addTlpParam(string $name, $value): void
{
$this->smarty->assign($name, $value);
}
public function display(): void
{
try {
$this->smarty->display($this->template);
} catch (\SmartyException $e) {
} catch (\Exception $e) {
}
}
}
my controller
class product extends Controller
{
function __construct()
{
}
public function index($id)
{
$productInfo = $this->model->productInfo($id);
print_r($productInfo);
$this->view('product/index.php');
}
}
?>
my model
class model_product extends Model
{
function __construct()
{
parent::__construct();
}
function productInfo($id)
{
$sql = 'select * from tbl_product where id=:x ';
$stmt = self::$conn->prepare($sql);
$stmt->bindParam(':x', $id);
$stmt->execute();
$result = $stmt->fetch();
return $result;
}
}
app.php
class App{
public $controller='index';
public $method='index';
public $params= [];
function __construct()
{
if(isset($_GET['url'])){
$url=$_GET['url'];
$url=$this->parseUrl($url);
$this->controller=$url[0];
unset($url[0]);
if (isset($url[1]))
{
$this->method=$url[1];
unset($url[1]);
}
$params=array_values($url);
}
$controllerUrl='controlls/'.$this->controller. '.php.';
if (file_exists($controllerUrl)){
require ($controllerUrl);
$object=new $this->controller;
$object->model($this->controller);
if(method_exists($object,$this->method))
call_user_func_array([$object,$this->method],$this->params);
}
}
function parseUrl($url){
$url=filter_var($url,FILTER_SANITIZE_URL);
$url=rtrim($url,'/');
$url=explode('/',$url);
return $url;
}
it shows this error
Fatal error: Uncaught ArgumentCountError: Too few arguments to function product::index(), 0 passed in C:\xampp\htdocs\hermesmvc\core\app.php on line 40 and exactly 1 expected in C:\xampp\htdocs\hermesmvc\controlls\product.php:14 Stack trace: #0 C:\xampp\htdocs\hermesmvc\core\app.php(40): product->index() #1 C:\xampp\htdocs\hermesmvc\index.php(9): App->__construct() #2 {main} thrown in C:\xampp\htdocs\hermesmvc\controlls\product.php on line 14
Replace in your app.php $params=array_values($url); by $this->params=array_values($url);
Because if you dont set $this->params In construtor, it will stay empty. Quite like what you made for method and controller.
I will try to explain myself the best way possible. I am trying to start with OOP in PHP. I started this way, i made a "main controller" with a construct where i initiated all my other controllers. I did this because i was hoping to share data along controllers.
class clsController{
public function __construct($smarty){
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
$this->o_clsSharedAdsController = new clsSharedAdsController($this->o_smarty);
$this->o_clsSharedUserController = new clsSharedUserController($this->o_smarty);
}
}
So far it looks pretty oke in my opinion. Now the thing is when i am in the class clsSharedUserController which looks like this:
class clsSharedUserController extends clsController{
// construct
public function __construct($smarty) {
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
}
}
I cannot access a function in the clsSharedAdsController. The controller looks like this.
class clsSharedAdsController extends clsController{
// construct
public function __construct($smarty) {
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
}
// ad details used for messages
public function getAdDetailsForMessage($ads_id){
echo $ads_id;
}
}
I am trying to do access it the following way
class clsSharedUserController extends clsController{
// construct
public function __construct($smarty) {
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
}
// ad details used for messages
public function getUserReviews($userReviews){
$this->o_clsSharedAdsController->getAdDetailsForMessage(1);
}
}
To be honest i expected to get my 1 echo-ed but i am getting this error:
Fatal error: Uncaught Error: Call to a member function getAdDetailsForMessage() on null in /home/vhosts/gamermarket.nl/httpdocs/includes/controllers/shared/clsSharedUserController.php:124
Stack trace:
#0 /home/vhosts/gamermarket.nl/httpdocs/includes/controllers/shared/clsSharedUserController.php(68): clsSharedUserController->getUserReviews(Array)
#1 /home/vhosts/gamermarket.nl/httpdocs/includes/controllers/clsReviewController.php(17): clsSharedUserController->getUserReviewsFromUsersId('0000000001')
#2 /home/vhosts/gamermarket.nl/httpdocs/reviews.php(10): clsReviewController->getReviews()
#3 {main} thrown in /home/vhosts/gamermarket.nl/httpdocs/includes/controllers/shared/clsSharedUserController.php on line 124
I am using a PDO class for my queries to get data they are set-up the same way as this clsController. I am probally missing some logic for a correct set-up to share my data along all classes without creating new instances all the time. You should be able to just make 1 instance of a class and share it among other classes, not?
If you want to use some clsSharedUserController's method in clsSharedAdsController
and use some clsSharedAdsController's method in clsSharedUserController
you need to redesign the class
In clsController
class clsController{
protected $o_smarty;
public function __construct($smarty){
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
}
public function getSharedUser()
{
return new clsSharedUserController($this->o_smarty);
}
public function getSharedAds()
{
return new clsSharedAdsController($this->o_smarty);
}
}
In clsSharedUserController
class clsSharedUserController extends clsController{
// construct
public function __construct($smarty) {
parent::__construct($smarty);
}
// ad details used for messages
public function getUserReviews($userReviews){
$sharedAds = $this->getSharedAds();
$sharedAds->getAdDetailsForMessage(1);
}
}
In clsSharedAdsController
class clsSharedAdsController extends clsController{
// construct
public function __construct($smarty) {
parent::__construct($smarty);
}
// ad details used for messages
public function getAdDetailsForMessage($ads_id){
echo $ads_id;
}
//use the method in share user class
public function someMethod(){
$sharedUser = $this->getSharedUser();
//TODO
}
}
I think your main class should not new child class inside construct
In clsSharedUserController
class clsController{
public function __construct($smarty){
if (is_object($smarty)) {
$this->o_smarty = $smarty;
} else {
throw new Exception("Smarty not set!");
}
}
}
In clsSharedUserController
class clsSharedUserController extends clsController{
protected $o_clsSharedAdsController;
// construct
public function __construct($smarty) {
parent::__construct($smarty);
$this->o_clsSharedAdsController = new clsSharedAdsController($smarty);
}
// ad details used for messages
public function getUserReviews($userReviews){
$this->o_clsSharedAdsController->getAdDetailsForMessage(1);
}
}
In clsSharedAdsController
class clsSharedAdsController extends clsController{
// construct
public function __construct($smarty) {
parent::__construct($smarty);
}
// ad details used for messages
public function getAdDetailsForMessage($ads_id){
echo $ads_id;
}
}
You have to create an instance of the clsSharedAdsController class before you can use its methods.
o_clsSharedAdsController = new clsSharedAdsController($smarty);
o_clsSharedAdsController->getAdDetailsForMessage(1);
First, Thanks a lot
My problem is that i have Page which (indexStatic.php) have content variable return and affect some head tags like include js files but when i start file is give this message:
I want to access variables which are displayControler.php in indexStatic.php
<b>Fatal error</b>: Uncaught exception 'Exception' with message 'js doesn't exist in this class' in C:\webServer\htdocs\blabla\admin\AdminPanel\core\modelAbstract.php:25
Stack trace:
#0 C:\webServer\htdocs\blabla\admin\AdminPanel\static\indexStatic.php(2): ModelAbstract->__set('js', '<script src="re...')
#1 C:\webServer\htdocs\blabla\admin\AdminPanel\core\tools.php(14): include('C:\webServer\ht...')
#2 C:\webServer\htdocs\blabla\admin\AdminPanel\core\displayControler.php(33): tools->includeFile('/static/indexSt...')
#3 C:\webServer\htdocs\blabla\admin\AdminPanel\core\displayControler.php(28): displayControler->getContentHtml('/static/indexSt...')
#4 C:\webServer\htdocs\blabla\admin\AdminPanel\core\displayControler.php(18): displayControler->setUrlTofunc(NULL)
#5 C:\webServer\htdocs\blabla\admin\AdminPanel\index.php(17): displayControler->showHtml()
#6 {main}
thrown in <b>C:\webServer\htdocs\blabla\admin\AdminPanel\core\modelAbstract.php</b> on line <b>25</b><br />
indexStatic.php is included in displayControler.php lets see files :
indexStatic.php File :
<?php
$this->js ='<script src="resources/scripts/editablegrid-2.0.1.js"></script> ';
$this->js .='<script src="resources/scripts/jquery-1.7.2.min.js" ></script>';
$this->js.='<script src="resources/scripts/demo.js" ></script>';
return'<div class="content-box"><!-- Start Content Box -->
<script type="text/javascript">
window.onload = function() {
datagrid = new DatabaseGrid();
};
</script>
</div>';
?>
displayControler.php
class displayControler extends ModelAbstract
{
protected $js;
protected $tools;
protected $title;
protected $meta;
protected $content='';
protected $urls=array(
'main'=>'static/aboutStatic.php'
);
public function __construct(){
$this->setTitle(defaultVar::$static['title']);
}
public function showHtml(){
$this->setUrlTofunc(#$_GET['cont']);
include 'static/adminStatic.php';
}
public function setUrlTofunc($url){
$this->tools=new tools();
if(isset($url) and isset($this->urls[$url]) ){
$this->getContentHtml($this->urls[$url]);
}else{
$this->getContentHtml(defaultVar::$static['filePath']);
}
}
public function getContentHtml($url){
$catch = $this->tools->includeFile($url);
$this->setContent($catch);
}
}
and modelAbstract.php is have :
abstract class ModelAbstract{
public function __call($name, $args){
$methodPrefix = substr($name, 0,3);
$methodProperty = strtolower($name[3]).substr($name,4);
switch ($methodPrefix){
case "set":
if (count($args) == 1)
$this->__set($methodProperty,$args[0]);
else
throw new \Exception("magic method only supports one argument");
break;
case "get":
return $this->__get($methodProperty);
break;
default:
throw new Exception("magic methods only supported for get and set");
}
}
public function __set($name,$value){
if (property_exists($this, $name))
$this->$name = $value;
else
throw new \Exception("$name doesn't exist in this class");
}
public function __get($name){
if (property_exists($this, $name))
return $this->$name;
else
throw new \Exception("$name doesn't exist in this class");
}
}
The $js property is protected so you can not access it directly. You have magics in the Model class which make the getter and setter for your properties.
This means it will go through the magic call. Try using $this->setJs("") instead of $this->js = "".
this is my first question
I Have following class
class ProDetection {
public function ProDetection ( ) { }
public function detect($word) {
............
}
public function getScore() {
return $score;
}
}
class SaveDetection {
public function SaveDetection($words) {
$proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
}
in other PHP file, i'm try to calling SaveDetection to getScore();
$konten = "xxxx xxxx xxx";
$save = new SaveDetection($konten);
print_r( $save->getScore() );
But i got an error message
Notice: Undefined property: SaveDetection::$proDetection in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22
Fatal error: Call to a member function getScore() on a non-object in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22
Please need your help
You never declare the the $proDetection member variable. Basically in your SaveDetection constructor you are declaring $proDetection as a local variable
class SaveDetection {
public function SaveDetection($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
private $proDetection;
}
EDIT:
PS. You should really use PHP's __construct() syntax instead of the old style of constructors. See here.
class SaveDetection {
public function __construct($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
Try this. Declare your variables as private (Coz if your code grows, it is hard to find what all the object or variables are used in the class.)
class SaveDetection {
private $proDetection = null;
public function __construct($words) {
$this->proDetection = new ProDetection();
for($i=0;$i<sizeof($words);$i++) {
$this->proDetection->detect($words[$i]);
}
}
public function getScore() {
return $this->proDetection->getScore();\\line 22
}
private $proDetection;
}