I want to call for a variable defined at a some point in the code. I use global keyword but it seems variable isn't recognized. When I set variable locally it works just fine. (it is the $title variable, it receives value of a static function of some object)
THIS ONE WORKS:
class Book {
public function represent() {
$titles = Title::all_by_id();
$title = $titles[$this->title_id];
return $title->represent().'_'.$this->id;
}
}
THIS ONE DOESN'T:
$titles = Title::all_by_id();
in another file
class Book {
public function represent(){
global $titles;
$title = $titles[$this->title_id];
return $title->represent().'_'.$this->id;
}
}
It sends an error:
PHP Fatal error: Call to a member function represent() on a non-object in
What are possible problems here?
I solved it, it was the problem that I set the $titles variable in a different subcontext of the main context than where Book class was defined
I solved the problem when I changed the place where I was defining that variable, I've put it in the main context.
Related
I have a class called DB_Bookings, within that class I have a function called updated_variables() within this is a simple script to look at the date of a published post and change the name of a variable accordingly.
Doing this, throughout my app I intend to use the variable and it will change dynamically per post depending on the date created.
I am struggling to call the variables from within another class. Please see my working below:
class DB_Bookings {
...
public function updated_variables() {
global $post;
$compare_date = strtotime( "2018-05-22" );
$post_date = strtotime( $post->post_date );
if($compare_date > $post_date) {
$weddingNameVariable = 'db-bookingsweddingname';
...
} else {
$weddingNameVariable = 'weddingName';
}
}
} // end DB_Bookings class
Then in my other class (in a file called class-db-bookings-admin.php)
class DB_Bookings_Admin {
...
public function save_metabox( $post_id, $post ) {
...
update_post_meta( $post_id, DB_Bookings::updated_variables($weddingNameVariable), $db_bookingsnew_weddingname );
...
}
} // end Class DB_Bookings_Admin
The idea here is that I can echo out the variable set in my DB_Bookings class and it can change based on the post date (this is essentially compensating for legacy variables as I overhaul the coding of the app).
However, it doesn't appear to be saving and I'm getting the following error
[22-May-2018 19:29:43 UTC] PHP Notice: Undefined variable: weddingNameVariable in /var/www/html/wp-content/plugins/db-bookings/admin/class-db-bookings-admin.php on line 853
Another approach based on comments.
class WeddingVariables {
//add all of the variables needed to this class
//you could create getters/setters to manage this data
$variableA = "data";
//get the variable
public function get_variable_a() {
return $this->variableA;
}
//set the variable
public function set_variable_a( $value ) {
$this->variableA = $value;
}
}
//a global variable
$WeddingVariables = new WeddingVariables();
//admin class
class DB_Bookings_Admin {
public function save_metabox( $post_id, $post ) {
global $WeddingVariables; //now we can access this within this method
//get the value of a variable from the class
$someVariable = $WeddingVariables->get_some_variable();
}
}
All I'm seeing that you're missing here is declaring your variable and treating it as static within the class itself.
public static $weddingNameVariable;
if($compare....)
self::$weddingNameVariable;
That's the basic bit you'll want to change, but there's a somewhat more complicated bit that's not correct: you're treating a non-static function as if it's static. So you may need to change your updated_variables function to be static itself. I also see that you're trying to do $post->post_date immediately after declaring global $post; but without initializing it to have any value. If you are trying to access post data sent from the client, try $_POST['some-key-here'] which is defined by PHP and accessible anywhere.
Once that's all straightened out, you can either have your updated_variables function return the new value you've set, or call the function the line before and then access the variable using DB_Bookings::$weddingNameVariable.
I notice a couple of things here. First, updated_variables() is not a static method, although you are calling it as a static method DB_Bookings::updated_variables(). To use that method statically, you would need to make it a static method via public static function updated_variables(). That is a discussion in itself however.
There are many ways to accomplish what you want, but you could do it with a global variable.
<?php
//this is global
$weddingNameVariable = false;
class DB_Bookings {
public function updated_variables() {
global $weddingNameVariable;
//now you can read/update this variable from within this method
}
}
class DB_Bookings_Admin {
public function save_metabox( $post_id, $post ) {
global $weddingNameVariable;
//now you can read/update this variable from within this method.
}
}
This may not be the OOP approach you are looking for, as you could utilize a static variable, but if that value you needs to change often, you'd be better managing it via other options in my opinion.
I would create an array with ID posts from inside a function, and get him outside the class.
My code:
<?php
class cat_widget extends WP_Widget {
private $newHomePost = array();
function widget($args, $instance){
//...
foreach($img_ids as $img_id) {
if (is_numeric($img_id)) {
$this->setNewHomePost($newsCounter,$post->ID);
$newsCounter++;
//...
}
}
}
function setNewHomePost($num, $value){
$newHomePost[$num] = $value;
}
function getNewHomePost(){
return "ID: ".$this->newHomePost[0];
}
}
$testA = new cat_widget();
echo $testA->getNewHomePost();
?>
I receive on screen this resuld:
ID:
(without the id)
But if I insert inside setNewHomePost() an echo for the array, I'll obtain correctly the array but inside and not outside class.
function setNewHomePost($num, $value){
$newHomePost[$num] = $valore;
echo $newHomePost[0];
}
So seem that the array works fine inside the "function widget", but doesn't works outside it.
Can someone help me, please?
function setNewHomePost($num, $value){
$newHomePost[$num] = $value;
}
This creates a local variable named $newHomePost, setting a value at an index and returning. Once it returns, the local variable disappears. From the linked manual page:
Any variable used inside a function is by default limited to the local function scope.
You want to set the class member property newHomePost instead:
function setNewHomePost($num, $value) {
$this->newHomePost[$num] = $value;
}
Update
This is how you currently have the get method defined:
function getNewHomePost() {
return "ID: " . $this->newHomePost[0];
}
I suspect you're still fiddling with this and trying to get it to work. If you really want to just only ever return the 0'th index, try something like this instead:
function getNewHomePost() {
return isset($this->newHomePost[0]) ? $this->newHomePost[0] : null;
}
When building a class remember that you cannot make any assumptions about what order your public methods can be called from another object or calling code (even if the calling code itself exists inside of the class. The methods are public, meaning anything can call them). The code above assumes nothing in that you do not have to call addNewHomePost prior to getNewHomePost. I imagine if you look in your logs you may see a few Notice: Undefined index.. type errors.
Also be sure to check on the calling side:
$myClass = new cat_widget;
$myClass->setNewHomePost(0, 'my new home post!');
$homePost = $myClass->getNewHomePost();
echo $homePost ? $homePost : 'None';
I think a better getter method would probably look like this:
function getNewHomePost($i) {
return isset($this->newHomePost[$i]) ? $this->newHomePost[$i] : null;
}
I get an error saying unexpected '(' when trying to do this in a class:
private $doglist = file_get_contents('dogdropdown.html');
Is that not allowed for some reason?
I also tried using a function like this:
public function getDogList(){
$list = file_get_contents('dogdropdown.html');
return $list;
}
which also didnt work. if I used include it does but doesnt inlcude it in the right place.
When you declare a class property you can only assign basic scalar values or null for variables that should reference objects. If the property needs to hold the result of some operation you either make it static or assign the result either in the constructor or a method of the class.
In order to do what you are trying to do you need the following:
class MyClass {
private $doglist;
function __construct() {
$this->doglist = file_get_contents('dogdropdown.html');
}
}
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
Later on I call the set_page_title() function like so
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
When I do I receive the error message:
Call to a member function set_page_title() on a non-object
So what am I missing?
It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes for the first parameter.
There's an easy way to produce this error:
$joe = null;
$joe->anything();
Will render the error:
Fatal error: Call to a member function anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if PHP would just say,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define anything() in on line <##>.
Usually you have build your class so that $joe is not defined in the constructor or
Either $objPage is not an instance variable OR your are overwriting $objPage with something that is not an instance of class PageAttributes.
It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable.
IE
$game = new game;
$game->doGameStuff($gameReturn);
foreach($gameArray as $game)
{
$game['STUFF']; // No longer an object and is now a standard variable pointer for $game.
}
$game->doGameStuff($gameReturn); // Wont work because $game is declared as a standard variable. You need to be careful when using common variable names and were they are declared in your code.
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
looks like different names of variables $objPortal vs $objPage
I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the page_properties function.
$objPage = new PageAtrributes;
function page_properties() {
global $objPage;
$objPage->set_page_title($myrow['title']);
}
I realized that I wasn't passing $objPage into page_properties(). It works fine now.
you can use 'use' in function like bellow example
function page_properties($objPortal) use($objPage){
$objPage->set_page_title($myrow['title']);
}
I have a template class which goes like this:
class Template{
public $pageTitle = "";
public function __construct($pageTitle){
$this->pageTitle = $pageTitle;
}
public function display(){
include "/includes/head.php";
include "/includes/body.php";
}
}
Now, I'm used to Java's workings but I don't understand why I'm getting an undefined variable ($pageTitle) error. The included files need to be able to access that variable. I know it's going to be very simple but I actually haven't found out why.
What do I need to do to allow includes to see this variable?
The includes will also have to use $this->pageTitle. Effectively, the include makes them part of the method body.
The included file lives in the same scope as your object. So you need to call:
$this->pageTitle
If you don't want to do the whole $this->, you can do something like the following... The extract function will extract the array $this->data into variables with names respective to the key/index of each item. So now you will be able to do echo $pageTitle;
class Template{
public $data = Array();
public function __construct($pageTitle){
$this->data['pageTitle'] = $pageTitle;
}
public function display(){
extract($this->data);
include "/includes/head.php";
include "/includes/body.php";
}
}
Scope is a little different in PHP than in java.
For your specific case you need
$this->pageTitle
To access a variable declared outside the class, you'll need to make it global
global $myVar;