php constructor variable not getting accessed in the functions below - php

I have initialized a new instance of a library in the __construct(){} method of a PHP class and equated it to a variable,
but now I want to use this variable to access methods of the library inside another function but PHP is not allowing me do that.
class Demo
{
public function __construct()
{
parent::__construct(new PaymentModel);
$this->api = new Api(config("razorpay", "key_id"), config("razorpay", "key_secret"));
}
public function createOrder()
{
$order = $api->order->create();
echo '<pre>';
var_dump($order); die;
}
}
I looked at the __construct documentation and some other answers here on stack overflow but all they did was confuse me more than helping me out.
Please help me figure this out as I am a starter myself in tech.

To be able to use $this->api in your class, you will need to set it as an attribute.
so :
class Demo
{
private $api;
public function __construct()
{
parent::__construct(new PaymentModel);
$this->api = new Api(config("razorpay", "key_id"), config("razorpay", "key_secret"));
}
public function createOrder()
{
$order = $this->api->order->create();
echo '<pre>';
var_dump($order); die;
}
}
Also, as notified by other, you are to construct a parent class while your class 'Demo' does not extend any other class.

You have defined api as a class variable (property). Use $this->api to acces this class variable (property) in other methods of your class.
// This class probably inherits some base class
class Demo extends BaseDemo
{
public function __construct()
{
parent::__construct(new PaymentModel);
$this->api = new Api(config("razorpay", "key_id"), config("razorpay", "key_secret"));
}
public function createOrder()
{
$order = $this->api->order->create();
echo '<pre>';
var_dump($order); die;
}
}
Also check your class definition - if parent::__construct() is called, then your class probably inherits some base class. If this is not the case, remove parent::__construct() call.

To access object variables you need to use $this. In your case change the first line in createOrder() to $order = $this->api->order->create();
Also you appear to be trying to run the classes parents constructor in your constructor. But the class doesn't have a parent.

you are calling parent::__construct(new PaymentModel); on a class which doeasn't extend any base class.

declare variable $api in a class then only accessible to other function body

Related

How to use one function variable to another function in abstract class

abstract class Dropboxapi {
protected $webAuth;
protected function abi() {
require __DIR__.'/app/Dropbox/autoload.php';
self::start();
self::dropbox_auth();
}
public function start() {
$webAuth = new Dropbox\WebAuth($appInfo,$appName,'path',$csrfTokenStore);
}
public function dropbox_auth() {
$authUrl = $webAuth->start();
}
}
Dropboxapi::abi();
Here i have $webAuth object in start function. When I use this in dropbox_auth it shows Undefined variable: webAuth.
When i use $this->webAuth i'm getting Using $this when not in object context
i tried like self::webAuth also. This is showing Access to undeclared static property:. So I don't understand how to use that.
if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Many example are there for abstract class.Just check how you can or not.As you asked without abstract just define the class and function like below.Here all the variable and methods are $this context.
class Dropboxapi {
public $this->webAuth='';
public function abi() {
require __DIR__.'/app/Dropbox/autoload.php';
$this->webAuth = new
Dropbox\WebAuth($appInfo,$appName,'path',$csrfTokenStore);
}
public function dropbox_auth() {
$authUrl = $this->webAuth->start();
}
}
$dropbox = new Dropboxapi();
$dropbox->dropbox_auth();
You are defining things wrong. Abstract class, similar with interface, are tend to be used as "blueprint" class. It means they need to be extended by another classes to be used, and cannot be used by itself as is. Using $this in abstract class is fine, as in documentation of abstract by php.net: http://php.net/manual/en/language.oop5.abstract.php.
What you need to do, is to have another class that inherit / extends that DropBoxApi class of yours, ex:
class DropBoxApi2 extends DropBoxApi
{
}
As class DropBoxApi2 is inherited, then it already has functions and property of it's parent (DropBoxApi). And you can use it like (example):
$api = new DropBoxApi2();
$api->start();
Additionally, the double colon that you use is static operator. Which is far far different concept than abstract.
Sample Code. Replace with your requirement.
you have to make everything as static
abstract class Dropboxapi {
protected static $webAuth;
public static function abi() {
self::start();
self::dropbox_auth();
}
public static function start() {
self::$webAuth = new Stdclass();
}
public static function dropbox_auth() {
var_dump(self::$webAuth);
}
}
Dropboxapi::abi();

PHP static method call with namespace in member variable

is it possible to do something like this in php? I want to have a namespace in a member variable and just always be able to call every static method of that class like I'm doing below.
Of course my code doesn't work, but I'm just wondering if that is possible at all and that I'm close to a solution, or if that's completely out of the question and must always use the syntax:
\Stripe\Stripe::setApiKey(..);
Similar question for clarifications
NOTE: I cannot modify the Stripe class, it's important it stays untouched for when future devs must update the Stripe API
Simplified code:
class StripeLib
{
var $stripe;
public function __construct()
{
// Put the namespace in a member variable
$this->stripe = '\\'.Stripe.'\\'.Stripe;
}
}
$s = new StripeLib();
// Call the static setApiKey method of the Stripe class in the Stripe namespace
$s->stripe::setApiKey(STRIPE_PRIVATE_KEY);
Yes something like this is possible. There is is static class method which can be called which returns the namespace path of the class.
<?php
namespace Stripe;
Class Stripe {
public static function setApiKey($key){
return $key;
}
}
class StripeLib
{
public $stripe;
public function __construct()
{
// Put the namespace in a member variable
$this->stripe = '\\'.Stripe::class;
}
}
$s = (new StripeLib())->stripe;
// Call the static setApiKey method of the Stripe class in the Stripe namespace
echo $s::setApiKey("testKey"); //Returns testkey
I just tested it, yes you can do that in php.
But I think you violate Dependency Injection principle here.
The right way to do that is:
class StripeLib
{
var $stripe;
// make sure Stripe implements SomeInterface
public function __construct(SomeInterface $stripe)
{
// Stripe/Stripe instance
$this->stripe = $stripe;
}
}

Interacting with multiple PHP classes

I am learning on PHP classes. I can write a basic PHP classes but having trouble when accessing variables and functions from other classes.
My first class
Class First_class
{
public $options;
function __construct()
{
$this->options = get_option('theme_options'); //wordpress fn
}
function my_function() {
add_menu_page(...)
}
}
Class Second_class
{
public $first_class_object;
function __construct()
{
$this->first_class_object = new First_class();
//Trying to access $this->options here
}
}
new Second_class();
Class Third_class
{
public $first_class_object;
function __construct()
{
$this->first_class_object = new First_class();
//Trying to access $this->options here
}
}
new Third_class();
I am trying to access public variables from Class First_class using $first_class_object = new First_class(); in the second class and third classes. You see when I initiate new First Class in other classes add_menu_page() triggers two times. I am not sure how to access the variables and functions properly. May be constructors?
Sorry may be I am something wrong here?
I am looking for an experts suggestion.
Extend your classes.
An example is below using your code as an example. 3v4l demo is here and php extends docs are here.
<?php
class FirstClass
{
public $options;
public function __construct()
{
$this->options = ['yay']; //get_option('theme_options'); //wordpress fn
}
public function myFunction()
{
//
}
}
class SecondClass extends FirstClass
{
}
class ThirdClass extends FirstClass
{
}
$secondClass = new SecondClass();
var_dump($secondClass->options);
$thirdClass = new ThirdClass();
var_dump($thirdClass->options);
if you try accessing other class Properties, you could use className::propertyName
OR
if you wanna access properties within the class you can use self:: or $this.
know more about accessing properties and traverses under classes.
http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php
try extend class
class Third_class extends First_class
{
public $first_class_object;
function __construct()
{
$this->first_class_object = new First_class();
//Trying to access $this->options here
}
}
or use this construction for access to you class
$this->first_class_object->option

Can I/How to... call a protected function outside of a class in PHP

I have a protected function that is defined within a certain class. I want to be able to call this protected function outside of the class within another function. Is this possible and if so how may I achieve it
class cExample{
protected function funExample(){
//functional code goes here
return $someVar
}//end of function
}//end of class
function outsideFunction(){
//Calls funExample();
}
Technically, it is possible to invoke private and protected methods using the reflection API. However, 99% of the time doing so is a really bad idea. If you can modify the class, then the correct solution is probably to just make the method public. After all, if you need to access it outside the class, that defeats the point of marking it protected.
Here's a quick reflection example, in case this is one of the very few situations where it's really necessary:
<?php
class foo {
protected function bar($param){
echo $param;
}
}
$r = new ReflectionMethod('foo', 'bar');
$r->setAccessible(true);
$r->invoke(new foo(), "Hello World");
That's the point of OOP - encapsulation:
Private
Only can be used inside the class. Not inherited by child classes.
Protected
Only can be used inside the class and child classes. Inherited by child classes.
Public
Can be used anywhere. Inherited by child classes.
If you still want to trigger that function outside, you can declare a public method that triggers your protected method:
protected function b(){
}
public function a(){
$this->b() ;
//etc
}
If the parent's method is protected, you can use an anonymous class:
class Foo {
protected function do_foo() {
return 'Foo!';
}
}
$bar = new class extends Foo {
public function do_foo() {
return parent::do_foo();
}
}
$bar->do_foo(); // "Foo!"
https://www.php.net/manual/en/language.oop5.anonymous.php
You can override this class with another where you make this public.
class cExample2 extends cExample {
public function funExample(){
return parent::funExample()
}
}
(note this won't work with private members)
But the idea of private and protected members is to NOT BE called from outside.
Another option (PHP 7.4)
<?php
class cExample {
protected function funExample(){
return 'it works!';
}
}
$example = new cExample();
$result = Closure::bind(
fn ($class) => $class->funExample(), null, get_class($example)
)($example);
echo $result; // it works!
If you want to share code between your classes you can use traits, but it depends how you want use your function/method.
Anyway
trait cTrait{
public function myFunction() {
$this->funExample();
}
}
class cExample{
use cTrait;
protected function funExample() {
//functional code goes here
return $someVar
}//end of function
}//end of class
$object = new cExample();
$object->myFunction();
This will work, but keep in mind that you don't know what your class is made of this way. If you change the trait then all of your classes which use it will be altered as well. It's also good practice to write an interface for every trait you use.
here i can give you one example like below
<?php
class dog {
public $Name;
private function getName() {
return $this->Name;
}
}
class poodle extends dog {
public function bark() {
print "'Woof', says " . $this->getName();
}
}
$poppy = new poodle;
$poppy->Name = "Poppy";
$poppy->bark();
?>
or one another way to use with latest php
In PHP you can do this using Reflections. To invoke protected or private methods use the setAccessible() method http://php.net/reflectionmethod.setaccessible (just set it to TRUE)
I am using Laravel. i was facing issue while access protected method outside of class.
$bookingPriceDetails = new class extends BookingController {
public function quotesPrice( $req , $selectedFranchise) {
return parent::quotesPrice($req , $selectedFranchise);
}
};
return $bookingPriceDetails->quotesPrice($request , selectedFranchisees());
here BookingController is Class name from which i want to get protected method. quotesPrice( $req , $selectedFranchise) is method that i want to access in different Class.

Access parent properties in child using $this

I am trying to create a simple MVC my personal use and I could really use an answer to this simple question
class theParent extends grandParent{
protected $hello = "Hello World";
public function __construct() {
parent::__construct();
}
public function route_to($where) {
call_user_func(array("Child", $where), $this);
}
}
class Child extends theParent {
public function __construct() {
parent::__construct();
}
public function index($var) {
echo $this->hello;
}
}
$x = new theParent();
$x->route_to('index');
Now Child::index() this throws a fatal error: Using $this when not in object context but if I were to use echo $var->hello, it works just fine.
I know I can use $var to access all properties in the parent, but I would rather use $this.
By writing call_user_func(array("Child", $where), $this) you are calling the method statically. But as your method isn't static you need some kind of object instance:
call_user_func(array(new Child, $where), $this);
Documentation on callback functions.
You don't have an instance of Child to call a non-static method upon when you're doing $x->route_to('index'); The way you're calling the method, without having made an instance first, is implied static.
There are two ways to correct it. Either make the Child class's methods static:
class Child extends theParent {
public function __construct() {
parent::__construct();
}
static public function index($var) {
echo self::$hello;
}
}
...or make an instance of the child class for the parent to use:
class theParent extends grandParent{
protected $hello = "Hello World";
private $child = false
public function __construct() {
parent::__construct();
}
public function route_to($where) {
if ($this->child == false)
$this->child = new Child();
call_user_func(array($this->child, $where), $this);
}
}
Of course, both of these samples are rather generic and useless, but you see the concept at hand.
$this gives you access to everything visible/accessible in the current object. That can either be in the class itself (this) or any of it's parents public or protected members/functions.
In case the current class overrides something of a parent class, you can access the parent method explicitly using the parent keyword/label, whereas you add :: to it regardless if it is not a static method.
Protected variables exist only once, so you can not use parent to access them.
Is this info of use?

Categories