Create a function that can be used anywhere within Wordpress site - php

I want to create a number of functions in my plugin 'membershipintegration.php' which can be called anywhere on my Wordpress site.
I thought that if I created a class and defined a public function within the class in the membershipintegration.php I could use it wherever I liked.
class MembershipIntegration
{
public function switchmembership () {
echo 'some code'
}
}
However, it doesn't seem to work and I've used 'function_exists' on my sandbox page and it says the function isn't active.
Any thoughts much appreciated. Thank you.

Wordpress automatically load your membershipintegration.php when the plugin is active, then any function created inside this file or any other included file is automatically loaded and available in any place.
The recommendation is:
Create a file called functions.php
<?php
function myFunctionOne(){
//some code
}
and then in your membershipintegration.php use:
require __DIR__.DIRECTORY_SEPARATOR.'functions.php';

There's no such thing as a function inside a class. PHP classes consist of properties and methods. The keyword to define a user-defined method is function so it's a little confusing.
To access a public method, you first need an instance of that method. For instance:
$s = new MembershipIntegration();
Then you can access the public method:
$s->switchmembership();

<?php
require plugin_dir_path( __FILE__ ) . 'file-name.php';
new CLassName();
?>
put this code on your plugin index file then it can be call any where if your plugin is activate

Related

Mediawiki Call hook function from another file

Hello I need to save some content to database in MediaWiki when a new page is created.
So I added hook in my LocalSettings.php:
$wgHooks['PageContentSaveComplete'][] ='assign_responsibility';
But I need to call the function assing_responsibility() from a extension php file Responsibility.php not LocalSettings.
I am new at Mediawiki system and I cant find out How to tell MediaWiki where it can find required hook function?
Thank you
Hook values are PHP callables; they can be defined in any file as long as the file gets loaded before the hook gets called (or, if you use a class method instead of a global function, the class is registered via $wgAutoloadClasses).
The convention is that your extension (which I assume is called Responsibility) creates a hook file:
// ResponsibilityHooks.php
class ResponsibilityHooks {
public static function onPageContentSaveComplete(/*...*/) { /*...*/ }
// ...
}
and makes sure it can be autoloaded:
// Responsibility.php
$wgHooks['PageContentSaveComplete'][] = 'ResponsibilityHooks::onPageContentSaveComplete';
$wgAutoloadClasses['ResponsibilityHooks'] = __DIR__ . '/ResponsibilityHooks.php';

Classes - require conflict in constructor

I'm coding a Wordpress plugin and I'm not sure regarding the function name conflict..
I have a file named test_handling.php which contains the following content :
function testing() { echo 'test'; }
I included this file in a class constructor (file named testcls.class.php) :
class TestCls {
function __construct() {
require_once('test_handling.php');
testing();
}
function otherfunction() {
testing();
}
// ...
}
In this case, I would like to know if the testing() function is only available in the TestCls class, or can it create conflicts if an other WP plugin has a function with the same name ?
Even with the same name, the functions will have different scope if defined as class method. To make a call to a regular function you will do the following:
testing();
and the result will be:
'test'
the class method need an instance of the class or be statically called. To call the method class you will need the following formats:
$class->test();
or
OtherPlugin::test();
To sum up, the function test will be different if defined as class method. Then, you will not have conflicts.
Other way to encapsulate your function and make sure you are using the right one is with namespaces. If you use a namespace in your test_handling.php
<?php
namespace myname;
function testing(){echo 'test';}
?>
You will access the function test like this:
<?php
require_once "test_handling.php";
use myname;
echo myname\testing();
Now you are sure about the function you are calling.
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
from include in PHP manual
Which means that yes, you can have conflicts.

CakePHP How to call a controller function from an external function

I'm having trouble with accessing the session in an external .php script located in webroot.
Thought I'd write a function getSession() in one of my controllers and try to call it in the .php file.
So in steps:
I have file.php
In a controller I have a function getSession().
How to call the controllers function in the file.php?
Thank you.
EDIT
Meanwhile I fixed my bug, but still am curious how this is done and want other stack users to find a good answer to this so:
Its exactly like this:
In UsersController I have a function:
public function getSession() {
return $_SESSION['Auth']['User']['user_id'];
}
That I want to let's say print (for example) like this: print_r(Users.getSession) in the file test.php located in webroot/uploadify/test.php.
This file is not a class, but if it is required, then it shall be :)
#CaboOne: Maybe your answer was correct, I just wasnt sure what code to call (and enter) where :)
Supposed I have the following php file in webroot folder:
<?php
class TestingClass {
function getName(){
return "Test";
}
}
?>
I would do the following:
// This would bring you to your /webroot folder
include $_SERVER['DOCUMENT_ROOT'].'/another_file.php';
// Initializing the class
$example = new TestingClass;
// Call a function from the initialized class
$a_value = $example->getName();
// If you want to use $a_value in the view, you can then set
$this->set('a_value', $a_value);

Can spl_autoload be placed in another file?

I'm currently making my first website with PHP. Rather than writing autoload for each individual page, I wish to create one file with a general autoload ability.
Here is my autoloadControl.php:
// nullify any existing autoloads
spl_autoload_register(null,false);
//specify extensions that may be loaded
spl_autoload_extensions('.php. .class.php');
function regularLoader($className){
$file = $className.'.php';
include $file;
}
//register the loader function
spl_autoload_register('regularLoader');
Here is my index.php file:
require("header.php");
require("autoloadControl.php");
$dbConnection = new dbControl();
$row=$dbConnection->getLatestEntry();
Currently, the $dbConnection = new dbControl() gives me the following error:
Fatal error: Class 'dbControl'
So my question is, is there a way to use autoload this way or must I place it at the top of every PHP file I write that uses another file?
Placing spl_autoload in an external file is both valid and a good practice for making your code more maintainable--change in one place what could be 10, 20, or more.
It appears that your dbControl class is not being provided in the code you provided. Assuming you are including the class before referencing it, and the class works properly, then you should have no problem accomplishing this task.
require("header.php");
require("autoloadControl.php");
$dbConnection = new dbControl(); // Where is this class located?
Here is an OOP approach for your autoloadControl.php file:
<?php
class Loader
{
public static function registerAutoload()
{
return spl_autoload_register(array(__CLASS__, 'includeClass'));
}
public static function unregisterAutoload()
{
return spl_autoload_unregister(array(__CLASS__, 'includeClass'));
}
public static function registerExtensions()
{
return spl_autoload_extensions('.php. .class.php');
}
public static function includeClass($class)
{
require(PATH . '/' . strtr($class, '_\\', '//') . '.php');
}
}
?>
Your problem is not related to where you are defining your callback, but how.
Using spl_autoload_extensions('.php') would achieve the same thing as your custom callback; you don't need both if your callback is as simple as this. Your comment is also wrong - calling spl_autoload_register with no arguments will not clear current callbacks, but it will register the default callback.
However, in your code, you have specified the argument to spl_autoload_extensions incorrectly - it should be a comma-separated list of extensions. So I think what you want is this:
// Tell default autoloader to look for class_name.php and class_name.class.php
spl_autoload_extensions('.php,.class.php')
// Register default autoloader
spl_autoload_register();
// READY!
The main difference this will make from your code is that the default autoloader will look for 'dbcontrol.php' (all lower-case) whereas yours will look for 'dbControl.php' (case as mentioned in PHP code). Either way, you certainly don't need both.

How can I make a regular variable accessible in files included by a class method?

I have a php site which flows as shown below. Please note I'm leaving out most of the code (wherever theres an ellipses).
index.php
include template.php
...
$_template = new template;
$_template->load();
...
template.php
class pal_template {
...
public function load() {
...
include example.php;
...
}
example.php
...
global $_template;
$_tempalate->foo();
...
Now, this works fine. However, I end up having a ton of files that are displayed via the $_template->load() method, and within each of these files I'd like to be able to make use of other methods within the template class.
I can call global $_template in every file and then it all works fine, but if possible I'd really like for the object $_template to be available without having to remember to declare it as global.
Can this be done, and what is the best method for doing it?
My goal is to make these files that are loaded through the template class very simple and easy to use, as they may need to be tweaked by folks who basically know nothing about PHP and who would probably forget to put global $_template before trying to use any of the $_template methods. If $_template were already available in example.php my life would be a lot easier.
Thanks!
You can define globals before you include 'example.php'.
global $_template;
include 'example.php'
Or you could do this:
$_template = $this;
include 'example.php'
Or inside example.php:
$this->foo();
The use of global is strongly not recommended.
By the way, consider this :
-> index.php
$_template = new template;
$_template->load();
-> template.php
class template {
public function load() {
include 'example.php';
}
public function showMessage($file) {
echo "Message from '{$file}'";
}
}
-> example.php
<?php
$this->showMessage(__FILE__);
Will output something like
Message from '/path/to/example.php'
I recommend you to not use "global", as Yanick told you as well.
What you probably need is the Registry design pattern. Then you can add the template to the registry and give it to every object. In general I would recommend you to learn about design patterns. Here are some more you could learn.

Categories