How to initialize instance properties? - php

I have sample code in my Class:
public $themePath = "layouts/inbox/";
public $theme = $this->themePath."theme-limitless.";
public $inboxView = $this->theme."inbox";
And here my code not work. I must save my theme name in one var and path to theme in another var and use view using theme name. Now I have error:
Constant expression contains invalid operations:
public $theme = $this->themePath."theme-limitless."; // Error line
Generaly I must get path in var $inboxView:
$inboxView = "layouts/inbox/theme-limitless.inbox";

You can initializate class properties in __construct method:
class MyClass
{
public $themePath = "layouts/inbox/";
public $theme;
public $inboxView;
function __construct() {
$this->theme = $this->themePath . "theme-limitless.";
$this->inboxView = $this->theme . "inbox";
}
}

Related

How To Pass Arguments To new Class & Define Variables

I'm trying to modify the plugin function in the original PHP class named My_Widget_Admin which i have copied over from a plugin to my theme, but get Fatal error Too few arguments to function My_Widget_Admin
Here is the code i added in my theme :
class Custom_Admin extends My_Widget_Admin {
function item_select() {
// Code
}
}
$new = new Custom_Admin;
$new->item_select();
I think it has something to do with this code from the plugin :
private $_instance;
private $_widget_object;
function __construct( $instance, $widget_object ) {
$this->_instance = $instance;
$this->_widget_object = $widget_object;
$this->form();
}
I need to pass these 2 arguments $instance, $widget_object to the new function Custom_Admin.
How do i do that?
Passing arguments to a constructor must be done when the class gets instantiated. This is done with the new keyword.
class Custom_Admin extends My_Widget_Admin {
function item_select() {
// Code
}
}
$new = new Custom_Admin($instance, $widget_object);
$new->item_select();

Using classes outside of the current directory in PHP

I have two folders in my directory:
Plugins
Classes
The Plugins folder contains two files: Sample.php and Plugins.php.
Sample.php is just a class with one function that extends the Plugins class. The Plugins class tries to create a new instance of the base class which is located in the Classes folder.
Plugins/Sample.php:
class Sample extends Plugins {
public $eggs;
public $pounds;
public function __construct() {
$this->eggs = "100";
$this->pounds = "10";
}
public function OnCall() {
echo "{$this->eggs} eggs cost {$this->pounds} pounds, {$this->name}!";
}
}
Plugins/Plugins.php:
class Plugins {
public $name;
public function __construct() {
include '../Classes/Base.php';
$base = new Base();
$this->name = $base->name;
}
}
Classes/Base.php:
class Base {
public $name = "Will";
public function Say() {
echo $this->name;
}
}
Index.php includes everything in the Plugins folder and is supposed to execute OnCall(). It is giving the following error messages:
Warning: include(../Classes/Base.php) [function.include]: failed to
open stream: No such file or directory in
/Applications/XAMPP/xamppfiles/htdocs/Plugins/Plugins/Plugins.php on
line 6
Warning: include() [function.include]: Failed opening
'../Classes/Base.php' for inclusion
(include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear')
in /Applications/XAMPP/xamppfiles/htdocs/Plugins/Plugins/Plugins.php
on line 6
Fatal error: Class 'Base' not found in
/Applications/XAMPP/xamppfiles/htdocs/Plugins/Plugins/Plugins.php on
line 7
Index.php (if it helps):
foreach(glob('Plugins/*.php') as $file) {
require_once $file;
$class = basename($file, '.php');
if(class_exists($class)) {
$obj = new $class;
$obj->OnCall();
}
}
What I need to do is use the Base class in classes outside of the Classes folder. How can I do so?
You need to call the parent's constructor in your Sample class.
class Sample extends Plugins {
public $eggs;
public $pounds;
public function __construct() {
parent::__construct();
$this->eggs = "100";
$this->pounds = "10";
}
public function OnCall() {
echo "{$this->eggs} eggs cost {$this->pounds} pounds, {$this->name}!";
}
}
You probably want to take advantage of __autoload (http://ca1.php.net/manual/en/function.autoload.php)
Using this function will allow you to load up your classes easily no matter what directory they're in.
Simple Example:
function __autoload($classname) {
$path = "path/to/Classes/$classname.php";
if(file_exists($path)) {
require_once $path;
}
}
This means you would be able to remove your include statement from your Plugins class and simply keep the declaration $base = new Base(); and __autoload will be magically called and load up the correct file.

PHP OOP error that I cannot understand

I try to extend the CheckfrontAPI class with my new class.
In my case I use the Singleton pattern in order to load only one instance at a time of my class and I get that error
Fatal error: Declaration of CheckFrontIntegrator::store() must be compatible with that of CheckfrontAPI::store() in /home/my_web_site/public_html/wp-content/plugins/checkfront/class/Checkfront_Integration.php on line 83
Any idea on how to solve that issue ?
Here is the CheckfrontAPI source code : https://github.com/Checkfront/PHP-SDK/blob/master/lib/CheckfrontAPI.php
And here is my class that extends that class:
<?php
class CheckFrontIntegrator extends CheckfrontAPI
{
private static $instance = null;
public $tmp_file = '.checkfront_oauth';
final protected function store($data = array())
{
$tmp_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR. $this->tmp_file;
if(count($data))
{
file_put_contents(
$tmp_file,
json_encode(
$data,
true
)
);
}
elseif(is_file($tmp_file))
{
$data = json_decode(
trim(
file_get_contents(
$tmp_file
)
),
true
);
}
return $data;
}
public function session($session_id, $data = array())
{
$_SESSION['checkfront']['session_id'] = $session_id;
}
public static function instance($data)
{
if(!isset(self::$instance))
{
self::$instance = new CheckFrontIntegrator($data);
}
return self::$instance;
}
public function __construct($data)
{
if(session_id() == '')
{
session_start();
}
parent::__construct($data, session_id());
}
}
?>
And I initiate the new instance of that class like that:
$this->checkfront_integrator = CheckFrontIntegrator::instance($args);
where args are all the important information needit by the class to initiate a new object
AFTER EDIT
I have change my method store from:
final protected function store($data = array())
....
to
protected function store($data)
....
and the problem still occure :(
CheckfrontAPI is an abstract class? in this case your CheckFrontIntegrator::store() arguments count must be identical to original declaration
EDIT
I see on github
abstract protected function store($data);
your override must be:
protected function store($data) {
}
You are extending CheckfrontAPI. CheckfrontAPI has a method store(). If you override that method you must do it properly.
Post the code of CheckfrontAPI and your class Checkfront_Integration: when can understand what's the problem.
When you want to extent the functionality of an existing class by writing your own class and the class you are extending is is an abstract one, you'll need to make sure that the function calls are compatible.
What does this mean?
If the class you are extending has this function call for example :
function walk($direction, $speed = null);
Then you will have to honor the function signature in your implementation - that means you'll still have to have to pass two function arguments in your version.
You will not be able to alter is to be like this :
function walk($direction, $speed, $clothing);

How to share a dynamic variable between files in PHP(5)?

I have an object of some class that obeys the singleton pattern. I need to initialize it in one file and then use it in others. I don't know how to do this, here is what I tried :
//myClass.php
class myClass
{
private static $instance = null;
private function __construct($args)
{
//stuff
}
public function Create($args)
{
self::$instance = new myClass($args);
return self::$instance;
}
public function Get()
{
return self::$instance;
}
}
//index.php
<?php
require_once('myClass.php');
$instance = myClass::Create($args);
?>
Test Me!
//test.php
echo(is_null(myClass::Get())); //displays 1
So the problem is that from test.php, myClass::get() always returns null!
I have also tried to store the instance in the $_SESSION, which gives me the same result. Can you please point me in the right direction?
You should include file with the class difinition in each file where it used (and it should be included before it will in use).
<?php // filename: test.php
include_once("myClass.php");
$oClassInstance = myClass::Get();
var_dump($oClassInstance);
BTW
You don't need to define those two methods Create and Get. You can create only one method called getInstance:
// only one instance of the class
private static $_oInstance = null;
public static function getInstace()
{
if (!self::$_oInstance)
{
self::$_oInstance = new self();
}
return self::$_oInstance;
}
And then you can use it like:
<?php // filename: index.php
include_once("myClass.php");
// if instance does not exist yet then it will be created and returned
$oClass = myClass::getInstace();
<?php // filename: test.php
include_once("myClass.php");
// the instance already created and stored in myClass::$_oInstance variable
// so it just will be returned
$oClass = myClass::getInstance();
UPD
If you have to put some arguments into constructor just use predefined arguments:
private function __construct($aArg)
{
// this code will be launched once when instance is created
// in the any other cases you'll return already created object
}
public static function getInstance($aArgs = null)
{
if (!self::$_oInstance)
{
self::$_oInstance = new self($aArgs);
}
return self::$_oInstance;
}
ANSWER
Sorry that you have to scroll a few screens to find this =)))
The reason why you can't use myClass::Get() in you context is that you have 2 scripts that means - two different programs.
Singleton should be used within a single application (one script).
So in your case, correct usage will be module system:
- index.php
- main.php
- test.php
// file: index.php
include_once "myClass.php"
$module = $_GET["module"];
include_once $module ".php";
// file: main.php
$oClass = myClass::Create($someArgs);
var_dump($oClass); // you'll see you class body
// file: test.php
$oClass= myClass::Get();
var_dump($oClass); // you'll see the same class body as above
And your links will be:
index.php?module=main
index.php?module=test
The Create() function need to check whether $instance property already has a value before creating a new object. For example
public function Create()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
In test.php you can just call myClass::Create(), no need to have the Get() function at all

Zend_Layout + helperClass

I am try to use helperClass in Zend_Layout options.
I create a class:
class Helper_Testi extends Zend_Controller_Action_Helper_Abstract{
public function init(){
echo "111111111";
$this->fff = 'hello from Helper';
}
public function getMessage(){
echo "==============";
return "message";
}
}
and in Bootstrap.php try add it to Zend_Layout:
$options = array('layout' => 'layout','helperClass'=>'../application/controllers/helper/Testi');
$layout = new Zend_Layout();
$layout->startMvc($options);
But when I reload browser I see Exception:
Fatal error: Uncaught exception 'Zend_Exception' with message 'File "../application/controllers/helper/Testi.php" does not exist or class "../application/controllers/helper/Testi" was not found in the file'
What I do wrong? Help me please.
Try to use APPLICATION_PATH constant in your path
You need place your helper class in correct place.
E.g. in my bootsrap there are such lines:
protected function _initViewHelpers() {
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->addHelperPath('Icc/View/Helper' , 'Icc_View_Helper');
}
And helper files will be located in this folder: Icc\View\Helper\
Edit:
E.g. I have file FormDropdown.php
with such content:
class Icc_View_Helper_FormDropdown extends Zend_View_Helper_Abstract {
function formDropdown($name = '')
{
return "<select name='$name' id='$name'></select>";
}
}
In view I can use this helper in this way:
<?=$this->formDropdown('icc_info_salutation')?>

Categories