how to visit the method in the child class from extends? - php

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();
?>

Related

Cannot store array values into $sum

i made this student class
<?php
Class Student
{
private $name;
private $amountOfGrades;
private $grades=array();
function __construct(string $name,int $amountOfGrades){
$this->name=$name;
$this->amountOfGrades=$amountOfGrades;
}
function setGrades(...$grade)
{
for($i=0;$i<$this->amountOfGrades;$i++)
$this->grades[$i]=$grade;
}
function getGrades(){
return $this->grades;
}
function getAvg(){
$sum=0;
for($i=0;$i<count($this->grades);$i++)
$sum+=$this->grades[$i];
return $sum/$amountOfGrades;
}
}
?>
and this is where i test it
<?php
require_once "studentClass.php";
$Jack = new Student("Jack",3);
$Jack->setGrades(100,50,69);
print_r($Jack->getAvg());
?>
the problem is that i keep getting this error
Fatal error: Uncaught TypeError: Unsupported operand types: array + null in D:\xamp\htdocs\studentClass.php:27 Stack trace: #0 D:\xamp\htdocs\testStudent.php(6): Student->getAvg() #1 {main} thrown in D:\xamp\htdocs\studentClass.php on line 27
how am i supposed to store the amount into sum to return the avg if i cant use +=
thanks in advance
Your setGrades was the problem, you passed the whole grade array to every single element. Also you have to use $this->amountOfGrades not $amountOfGrades. Take a look ;)
<?php
Class Student
{
private $name;
private $amountOfGrades;
private $grades=array();
function __construct(string $name,int $amountOfGrades){
$this->name=$name;
$this->amountOfGrades=$amountOfGrades;
}
function setGrades(...$grade)
{
for($i=0;$i<$this->amountOfGrades;$i++)
$this->grades[$i]=$grade[$i];
}
function getGrades(){
return $this->grades;
}
function getAvg(){
$sum=0;
for($i=0;$i<count($this->grades);$i++) {
$sum+=$this->grades[$i];
}
return $sum / $this->amountOfGrades;
}
}
$Jack = new Student("Jack",3);
$Jack->setGrades(100,50,69);
print_r($Jack->getAvg());
?>

Too few arguments to function php

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.

Fatal error: Constant expression contains invalid operations in /PATH/initClass.php on line 5

I am getting the following error!
Fatal error: Constant expression contains invalid operations in >/PATH/initClass.php on line 5
For the code:
<?php
Class init
{
public const THEME = "aman/dev/frontend/";
private $root = dirname(__dir__)."/aman/dev/fontend/";
public function getFile($name,$value)
{
list(
$title
) = $value;
}
}
?>
I can't seem to figure out what's is happening.
Help would be appreciated.
Your problem is that you are using a function operation to set a value to a class variable. To fix your problem, use the following code (i.e. move initialization to the constructor)
<?php
Class init
{
public const THEME = "aman/dev/frontend/";
private $root;
public function __construct() {
$this->root = dirname(__dir__)."/aman/dev/fontend/";
}
public function getFile($name,$value)
{
list(
$title
) = $value;
}
}
?>

Why I get "Uncaught Error: Call to a member function getFbPage() on null"?

I'm trying to register my custom widget in Wordpress. Unfortunately I came across a problem in communication with my another class FacebookServices. I can not figure out why I still getting error Uncaught Error: Call to a member function getFbPage() on null.
Here is a class where I am creating the widget which is pretty standard until I want to call html code into my function widget():
<?php
/**
* Facebook Page widget
*/
namespace Inc\Api\Widgets;
use WP_Widget;
use Inc\Plugins\FacebookServices;
class FbPage extends WP_Widget
{
public $fb_services;
public $widget_ID;
public $widget_name;
public $widget_options = array();
public $control_options = array();
public function __construct()
{
$this->widget_ID = 'fb_page';
$this->widget_name = 'Facebook Page';
$this->widget_options = array(
'classname' => $this->widget_ID,
'description' => 'Widget of Facebook Page',
'customize_selective_refresh' => true
);
$this->control_options = array();
}
public function register()
{
parent::__construct( $this->widget_ID, $this->widget_name, $this->widget_options, $this->control_options );
add_action( 'widgets_init', array( $this, 'widgetInit') );
$fb_services = new FacebookServices();
}
public function widgetInit()
{
register_widget( $this );
}
public function widget( $args, $instance )
{
echo $this->fb_services->getFbPage(); // <= line 58 from error
}
...
And here is the calling class:
<?php
/**
* Ensure Facebook integration
*/
namespace Inc\Plugins;
class FacebookServices
{
public $url;
public function __construct()
{
$this->url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
public function theFbLikes()
{
echo '<div class="fb-plugin-wrapper js-fbPlugin likes rendering">';
echo '<div class="fb-like" data-href="' . $this->url . '" data-layout="standard" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div>';
echo '</div>';
}
public function getFbPage()
{
return 'test';
}
}
I suppose to get 'test' but every time I call function getFbPage() I get error:
Fatal error: Uncaught Error: Call to a member function getFbPage() on null in C:\xampp\htdocs\dev1\wp-content\themes\tomva\inc\Api\Widgets\FbPage.php:58 Stack trace: #0 C:\xampp\htdocs\dev1\wp-includes\class-wp-widget.php(372): Inc\Api\Widgets\FbPage->widget(Array, Array) #1 C:\xampp\htdocs\dev1\wp-includes\widgets.php(743): WP_Widget->display_callback(Array, Array) #2 C:\xampp\htdocs\dev1\wp-content\themes\tomva\single.php(56): dynamic_sidebar('static') #3 C:\xampp\htdocs\dev1\wp-includes\template-loader.php(74): include('C:\\xampp\\htdocs...') #4 C:\xampp\htdocs\dev1\wp-blog-header.php(19): require_once('C:\\xampp\\htdocs...') #5 C:\xampp\htdocs\dev1\index.php(17): require('C:\\xampp\\htdocs...') #6 {main} thrown in C:\xampp\htdocs\dev1\wp-content\themes\tomva\inc\Api\Widgets\FbPage.php on line 58
I can not figure out what miss me.
From the code in your widget class, it seems the $fb_services property is declared but never initialized.
In the register() method, try changing this:
$fb_services = new FacebookServices();
into:
$this->fb_services = new FacebookServices();
You are not setting the class property fb_services, you could instantiate in your class __construct() method:
class FbPage extends WP_Widget
{
public $fb_services;
public $widget_ID;
public $widget_name;
public $widget_options = array();
public $control_options = array();
public function __construct()
{
$this->widget_ID = 'fb_page';
$this->widget_name = 'Facebook Page';
$this->widget_options = array(
'classname' => $this->widget_ID,
'description' => 'Widget of Facebook Page',
'customize_selective_refresh' => true
);
$this->control_options = array();
$this->fb_services = new FacebookServices();
}
$this->fb_services = new FacebookServices();
Just add this line in your constructor if you want to do it like this.
Keep in mind though to remove the last line of your register function cause you have already created the instance.
Or simple follow what you almost did in the register function if you are not going to use it in other functions.
$fb_services = new FacebookServices();
$fb_services->getFbPage();
Generally if you want to use the instance of your class in most of your functions then it's good to instantiate it in your constructor but if it's a one time thing just do it inside your function to be used once when this function is called.

Fatal Error - Call to undefined method "Customersss::throwError()"

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()

Categories