Php include array in class

Create an array inside a class with php

I have a class and I need to build an array. I usually can do that with a query and looping that but I am not sure how to do that with a class. Do I create the array before hand and turn it into a string? Here is my code sample

/** My Setting class **/ if ( ! class_exists( 'WC_my_setting' ) ) < class WC_my_setting < public function __construct() < // Init settings $this->settings = array( array( 'name' => __( 'My Setting', 'woocommerce-my-setting' ), 'type' => 'title', 'id' => 'wc_my_setting_options' ), array( 'name' => __( 'Name', 'woocommerce-my-setting' ), 'id' => 'wc_my_setting_category', 'type' => 'multiselect', //I want to have this->settings[options] populated with the array that the $category_options makes. 'options' => $category_options ), ) ), array( 'type' => 'sectionend', 'id' => 'woocommerce-my-setting' ), ); // Default options add_option( 'wc_my_setting_category', '' ); // Admin add_action( 'woocommerce_settings_image_options_after', array( $this, 'admin_settings' ), 20 ); add_action( 'woocommerce_update_options_catalog', array( $this, 'save_admin_settings' ) ); add_action( 'woocommerce_update_options_products', array( $this, 'save_admin_settings' ) ); > 

I can the code below on page templates just fine and I can output the array fine but I cannot get this working in the class in the admin area:

$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' ); $category_options = array(); if ( $categories ) < foreach ( $categories as $cat ) < $category_options[ $cat->slug ] = $cat->name; > > // print_r($category_options); 

How do I get the above loop in my class so the $category_options is placed in the $this->settings[options]

Источник

How to pass array to a class in php?

So when i call this function ispis() it doesn’t do anything but when i echo inside function __constructor it shows correct values of everything entered. Also when i comment first three lines above //$daniel = new User(«ivan»,»22″); line and uncomment this, ispis() works just fine. Would be nice if someone could explain to me why this is happening. Tnx in advance 🙂

$question_array is an array of User objects. So what exactly are you expecting $daniel = new User($question_array); to do?

You have defined 4 parameters on your constructor while you are passing only one to the last user instance . 4 parameters are expected ?

Also, there is no way that $daniel = new User(«ivan»,»22″); «works just fine». Depending on your version of PHP, you are, at best, getting a Warning, if not a Fatal Error.

3 Answers 3

By the looks of your code you’re trying to pass two new User instances into a new user («daniel»).

So basically User is expecting 4 arguments (age, name, height, weight). You’ve created Luka and Ivan correctly, but you’re passing those two Users as arguments when trying to create Daniel. You’re giving it Luka and Ivan when it wants age, name, height and weight.

If you simply want to pass an array to the constructor, just pass it as an argument on the new instance:

age = $args['age']; $this->name = $args['name']; $this->height = $args['height']; $this->weight = $args['weight']; > function getAge() < return $this->age; > > $question_array = [ 'name' => 'Daniel', 'age' => '22', 'weight' => '174', 'height' => '68' ]; $daniel = new User($question_array); echo $daniel->getAge(); // 22 ?> 

Источник

Читайте также:  Php если результат не найден

Using Array in PHP Class

I am exercising some PHP OOP and therefore I am creating a class to create a simple navigation menu ( with extensions in the future ) now I have build this class that works kinda.. with 1 menu item tough.. I don;t know how to use arrays in my class to use the class like

setMenuItem("home", "test"); echo $menu->display(); ?> 

as you see I should be able to give each menu item with the setMenuItem(); method. but since it does not use Arrays at the moment I only get the first value The class itself is as follows:

who can show me how to use arrays within the class in combination with a loop to create a menu with all given values? Thanks in advance.

4 Answers 4

You actually have two types, not one:

The MenuItemList would take care of managing the list. It could use an array internally. A code example for something very similar could be found in a previous answer: Array Object In Php.

Next to that the display() method does not belong into the two. Instead you should make your template that keen it knows how to output a menu list:

echo '
    '; foreach ($menu as $item) < echo '
    )" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
    )">edited May 23, 2017 at 10:26
    CommunityBot
    11 silver badge
    answered Nov 4, 2012 at 17:31
2
    What about MenuItemList::__toString()?
    – Madara's Ghost
    Nov 4, 2012 at 17:33
    @MadaraUchiha: That could output a plain-text representation for debugging purposes. However you could create a HTML decorator for that menulist that would output a HTML list with it's __toString() method. But the menuitems should not care about how they are output in specific. That's the job of some other part of the code.
    – hakre
    Nov 4, 2012 at 17:34
Add a comment|
0

At top of your class

$menuItems = array();
function setMenuItem($name, $value) < $this->menuItems[] = array($name, $value); > 

Edit: You could change the way they are stored, and prevent duplicates by using the nav "Name" as the key it is stored under, but I've kept it simple for ease of understanding.

Heres a more advanced sample

function setMenuItem($name, $value) < if(!in_array(array_keys($this->menuItems)), $name) < $this->menuItems[$name] = $value; > else < echo "That's already been added!"; //Handle this properly though >> 

Источник

Can I include code into a PHP class?

I want to make a PHP class, lets say Myclass.php. Now inside that class I want to define just the class itself and some instance variables. But all the methods must come from a Myclass_methods.php file. Can I just include that file into the class body? I have good reasons why I want to seperate this. In short, I'll have a backend in which I can change the business logic of a class, while all other things must remain untouched. The system maintains all the ORM and other stuff for me. But if this is a bad idea, it might be better to re-generate the whole class file after editing the business logic (so, the user-defined methods in this case). Performance question: If during one request Myclass.php is included just once, actually that Myclass_methods.php should also be included just once. Might be wrong. Experts?

10 Answers 10

No. You cannot include files in the class body.
In a file defining a class, you may only include files in a method body or outside the class body.

From your description I take you want this:

Running this code will result in

Parse error: syntax error, unexpected T_INCLUDE, expecting T_FUNCTION 

What is possible though is this

Doing it this way, will import the contents of the include file into the method scope, not the class scope. You may include functions and variables in the include file, but not methods. You could but should not put entire scripts into it as well and change what the method does, e.g.

However, patching the class this way to exhibit different behavior is not how you should do it in OOP. It's just plain wrong and should make your eyes bleed.

Since you want to dynamically change behavior, extending the class is also not a good option (see below why). What you really will want to do is write an interface and make your class use objects implementing this interface, thus making sure the appropriate methods are available. This is called a Strategy Pattern and works like this:

Now you got the contract that all Meowing Behaviors must obey, namely having a meow method. Next define a Meowing Behavior:

_meowing = $meowing; > public function meow() < $this->_meowing->meow() > > 

By adding the Meowing TypeHint to setMeowing, you make sure that the passed param implements the Meowing interface. Let's define another Meowing Behavior:

Now, you can easily interchange behaviors like this:

setMeowing(new RegularMeow); echo $cat->meow; // outputs 'meow'; // now to change the behavior $cat->setMeowing(new LolkatMeow); echo $cat->meow; // outputs 'lolz xD'; 

While you also could have solved the above with inheritance by defining an abstract BaseCat and meow method and then deriving concrete RegularCat and Lolkat classes from that, you have to consider what you want to achieve. If your cats will never change the way they meow, go ahead and use inheritance, but if your RegularCat and Lolkat is supposed to be able to do arbitrary meows, then use the Strategy pattern.

For more design patterns in PHP, check these resources:

The cats and meowings approach does it. I would have tried the dogs and barks approach but I realize that would have been a complete mess.

@T.Todua using traits is a very different thing that what is asked here, so no, the answer still stands and isn't obsolete.

Might it not be an idea to create the core class with the relevant base functionality and then extend this with the required methods - it seems like a more logical approach.

Also calling functions from the class A in source a.php to Class B in b.php would be better than include_once(). Something like Pimpl idiom.

I'll start by saying I'm not too clear why this problem is not best solved using a base class containing the methods, subclasses containing the data, and dynamic class loading. I'll assume you have a good reason.

Once your provider supports PHP 5.4 you can do what you want using traits.

if ($pet === 'dog') include 'dog.php'; elseif ($pet === 'cat') include 'cat.php'; else die('Unknown pet'); class Pet < use PetSounds; >$myPet = new Pet(); $myPet->speak(); 

You could make this even cleaner by naming both include files the same, putting them in different subdirectories, and using set_include_path() or defining an __autoload() function to select between them. Like I said though, this same problem could be solved better using inheritance. If you have a multiple-inheritance type problem though, if for instance you have four kinds of pets with five kinds of colors with three hair types and you need a different combination of methods for each of the 60 different classes, this is the right solution.

5.4 is currently just a Release Candidate (as of 2/24/2012) and even once released most hosts will not support it for many months - mine took 18 months after 5.3 was released before they would support it. Until then you must write entirely separate and complete class files. You can however format your classes with an eventual change to traits in mind.

Right now you can partially get what you want using magic methods and have an easy upgrade to traits when they are available.

if ($pet === 'dog') include 'dog.php'; elseif ($pet === 'cat') include 'cat.php'; else die('Unknown pet'); class Pet < public function __call($name, array $arguments) < array_unshift($arguments, $this); return call_user_func_array("TraitFunc_$name", $arguments); >> $myPet = new Pet(); $myPet->speak(); 
function TraitFunc_speak(Pet $that)
function TraitFunc_speak(Pet $that)

You are limited however in that your functions can not access private and protected class properties and methods and you can not use this method to provide magic methods such as __get(). Traits will solve both of those limitations.

Источник

Оцените статью