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.
Related
Here I want to use the code class Child_Site extends Site to extend the class Site, and the class Site is used with the __construct to receive $par1, $par2. When I use
$D=new Child_Site("ddd","gggg");$D->getTitle(); to visit his parent class, it is totally fine. But when I want to visit the child method, why it give the error?
Fatal error: Uncaught ArgumentCountError: Too few arguments to
function Site::__construct(), 0 passed in
D:\phpstudy_pro\WWW\index.php on line 39 and exactly 2 expected in
D:\phpstudy_pro\WWW\index.php:7 Stack trace: #0
D:\phpstudy_pro\WWW\index.php(39): Site->__construct() #1 {main}
thrown in D:\phpstudy_pro\WWW\index.php on line 7
<?php
class Site {
var $url;
var $title;
function __construct( $par1, $par2 ) {
$this->url = $par1;
$this->title = $par2;
}
function setUrl($par){
$this->url = $par;
}
function getUrl(){
echo $this->url . PHP_EOL;
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title . PHP_EOL;
}
}
class Child_Site extends Site{
var $category;
function setCate($par){
$this->category=$par;
}
function getCate(){
echo $this->category.PHP_EOL;
}
}
$D = new Child_Site("ddd","gggg");
$D->getTitle();
$s = new Child_Site;
$s->setCate("xx");
$s->getCate();
?>
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()
I have a class DashboardController as
class DashBoardController extends Controller
{
public $str;
public function __construct($str)
{
$this->str = $str;
echo $this->str;
}
public function dashboard(Request $request)
{
$obj = new DashBoardController("hello");
die;
}
}
it gives me Exception as
Unresolvable dependency resolving [Parameter #0 [ $str ]] in class App\Modules\User\Controllers\DashBoardController
What is the error here?
You need to pass default value if there is no dependency injected at the time of load.
class DashBoardController extends Controller
{
public $str;
public function __construct($str='')
{
$this->str = $str;
echo $this->str;
}
public function dashboard(Request $request)
{
$obj = new DashBoardController("hello");
die;
}
}
I am getting this error
Fatal error: Uncaught Error: Call to a member function escape_string() on null in C:\xampp\htdocs\url\classes\shortener.php:19 Stack trace: #0 C:\xampp\htdocs\url\shorten.php(10): Shortener->makeCode('stackove...') #1 {main} thrown in C:\xampp\htdocs\url\classes\shortener.php on line 19
i am designing my own url shortener but it gave me this error when i tested it.
The code i am using for this
This is the shorten file to get the input url
shorten.php
<?php
session_start();
require_once 'classes/shortener.php';
$s = new Shortener;
if(isset($_POST['url'])) {
$url = $_POST['url'];
if($code = $s->makeCode($url)) {
echo $code;
} else {
}
}
this is the file which shortens the url
shortener.php
<?php
class Shortener{
protected $db;
public function _construct(){
$this->db = new mysqli('localhost','root','','shortenedurl');
}
protected function generateCode($num){
return base_convert($num, 10, 36);
}
public function makeCode($url){
$url = trim($url);
if(!filter_var($url, FILTER_VALIDATE_URL)) {
return '';
}
$url = $this->db->escape_string($url);
$exists = $this->db->query("SELECT code FROM short_urls WHERE urlinput = '{$url}'");
if($exists->num_rows) {
return $exists->fetch_object()->code;
} else {
$insert = $this->db->query("INSERT INTO short_urls(urlinput, created) VALUES ('{$url}', NOW())");
$code = $this->generateCode($this->db->insert_id);
$this->db->query("UPDATE short_urls SET code ='{$code}' WHERE url ='{$url}'");
return $code;
}
}
public function getUrl($code){
}
}
The construct need to start with two of '_' so it must be '__' .
So you need to change public function _construct(){ to this public function __construct(){
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;
}