Search Results

Search found 1449 results on 58 pages for 'oop'.

Page 18/58 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • PHP: Array of objects is empty when I come to retrieve one from the array

    - by Tom
    Good morning, I am trying to load rows from a database and then create objects from them and add these objects to a private array. Here are my classes: <?php include("databaseconnect.php"); class stationItem { private $code = ''; private $description = ''; public function setCode($code ){ $this->code = $code; } public function getCode(){ return $this->code; } public function setDescription($description){ $this->description = $description; } public function getDescription(){ return $this->description; } } class stationList { private $stationListing; function __construct() { connect(); $stationListing = array(); $result = mysql_query('SELECT * FROM stations'); while ($row = mysql_fetch_assoc($result)) { $station = new stationItem(); $station->setCode($row['code']); $station->setDescription($row['description']); array_push($stationListing, $station); } mysql_free_result($result); } public function getStation($index){ return $stationListing[$index]; } } ?> As you can see I am creating a stationItem object per database row (which for now has a code and description) and I then push these on to the end of my array which is held as a private variable in stationList. This is code which creates this classes and attempts to access the properties on them: $stations = new stationList(); $station = $stations->getStation(0); echo $station->getCode(); I am finding that the sizeof($stationList) at the end of the constructor is 1 but then it is zero when we come to try to get an object from the array using the index. Therefore the error that I get is: Fatal error: Call to a member function getCode() on a non-object Please can someone explain to me why this is happening? I guess I am misunderstanding how object references work in PHP5.

    Read the article

  • iPhone Dev: Animating PNG Sequences

    - by Franky
    What is the best or recommended technique for animating PNG Sequences. Heres what I've learned: Do it Manually Using MutableArrays containing Strings, you can animate a UIImageView with a timer which increments an index number UIImage - animation methods This works, the only problem is to find if an image has completed its animation, you have to check the isAnimating BOOL, and to do that you need a timer. What is the best and recommended? Looking to do Oldschool game sprite animations, ie: Idle Animation Attack Animation Walk Animation ect... Let me know if any one has something. @lessfame

    Read the article

  • What's the deal with Java's public fields?

    - by Annan
    I've been reading two articles (1)(2) on javaworld.com about how all class fields should be private and getter/setter methods are just as bad. An object should act on the data it has rather than allowing access to it. I'm currently working on a University assignment for Connect Four. In designing the program the Agents playing the Game need access to the Board's state (so they can decide what to move). They also need to pass this move to the Game so it can validate it as a legal move. And during deciding what to move pieces are grouped into Threats with a start and end Points. Board, Threat and Point objects don't really do anything. They are just there to store related data that can be accessed in a human readable way. At the start of design I was representing Points on the board as two element int arrays, however that got annoying when creating points or referencing components of them. So, the class: public class Point { public int x; public int y; public Point(int x, int y){ this.x = x; this.y = y; } } Perfect in every way I can think of. Except it breaks every rule I've learned. Have I sinned?

    Read the article

  • JavaScript private methods

    - by Wayne Kao
    To make a JavaScript class with a public method I'd do something like: function Restaurant() { } Restaurant.prototype.buy_food = function() { // something here } Restaurant.prototype.use_restroom = function() { // something here } That way users of my class can: var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom(); How do I create a private method that my public buy_food and use_restroom methods can call but that users of the class can't call externally. In other words, I want my method implementation to be able to do: Restaurant.prototype.use_restroom = function() { this.private_stuff(); } But this shouldn't work: var r = new Restaurant(); r.private_stuff(); How do I define private_stuff as a private method so both of those hold true? I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.

    Read the article

  • PHP: Get instance of static class by string value

    - by Tirithen
    I'm working on a php web api that was handed to me with a lot of code that needs to be refactored. The ones that wrote the code wanted to include a static configuration class to an api resource and then get an instance of that class something like this: <?php $obj = "User"; $confObjectSuffix = "_conf"; $confObject = $obj.$confObjectSuffix; if ($confObject::inst()->checkMethod($method)) { ..... This gives the error "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ....." since $confObject is a string and not a object. I wrote some testcode: <?php $class = "User_conf"; echo "<pre>"; print_r($$class::Inst()); echo "</pre>"; class User_conf { private static $INSTANCE = null; public static function Inst() { if(User_conf::$INSTANCE === null) { User_conf::$INSTANCE = new User_conf(); } return User_conf::$INSTANCE; } } But can't get it to work with $$ either, is there some other way around this? I don't want to rewrite more than necessary.

    Read the article

  • Why this method does not use any properties of the object?

    - by Roman
    Here I found this code: import java.awt.*; import javax.swing.*; public class FunWithPanels extends JFrame { public static void main(String[] args) { FunWithPanels frame = new FunWithPanels(); frame.doSomething(); } void doSomething() { Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); p1.add(new JButton("B"), BorderLayout.WEST); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); p2.add(new JButton("G")); p2.add(new JButton("H")); p2.add(new JButton("I")); p2.add(new JButton("J")); p2.add(new JButton("K")); JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); p3.add(new JButton("M")); p3.add(new JButton("N")); p3.add(new JButton("O")); p3.add(new JButton("P")); c.setLayout(new BorderLayout()); c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); c.add(p3, BorderLayout.EAST); pack(); setVisible(true); } } I do not understand how "doSomething" use the fact that "frame" is an instance of the class JFrame. It is not clear to me because there is no reference to "this" in the code for the method "doSomething".

    Read the article

  • Easiest (simple) explanation of "prototype" in JavaScript?

    - by alexeypro
    Hello, Can somebody give me a resource (or just explanation? :-) of what "prototype" is and how it works in Javascript. May be comparison with something in Java? (not really necessary). But it should be as simple/easy as possible so inexperienced person just learning Javascript would understand (need to explain this to jr designer who is proficient with CSS/HTML, but not with Javascript). Thank you!

    Read the article

  • Multiple classes in Codeigniter

    - by Leon
    I want to create an array of objects, so what I did was to create a library but I can't figure out how to actually dynamically create instances of it in a loop and store each instance in an array. Can anyone tell me please?

    Read the article

  • Why is execution-time method resolution faster than compile-time resolution?

    - by Felix
    At school, we about virtual functions in C++, and how they are resolved (or found, or matched, I don't know what the terminology is -- we're not studying in English) at execution time instead of compile time. The teacher also told us that compile-time resolution is much faster than execution-time (and it would make sense for it to be so). However, a quick experiment would suggest otherwise. I've built this small program: #include <iostream> #include <limits.h> using namespace std; class A { public: void f() { // do nothing } }; class B: public A { public: void f() { // do nothing } }; int main() { unsigned int i; A *a = new B; for (i=0; i < UINT_MAX; i++) a->f(); return 0; } Where I made A::f() once normal, once virtual. Here are my results: [felix@the-machine C]$ time ./normal real 0m25.834s user 0m25.742s sys 0m0.000s [felix@the-machine C]$ time ./virtual real 0m24.630s user 0m24.472s sys 0m0.003s [felix@the-machine C]$ time ./normal real 0m25.860s user 0m25.735s sys 0m0.007s [felix@the-machine C]$ time ./virtual real 0m24.514s user 0m24.475s sys 0m0.000s [felix@the-machine C]$ time ./normal real 0m26.022s user 0m25.795s sys 0m0.013s [felix@the-machine C]$ time ./virtual real 0m24.503s user 0m24.468s sys 0m0.000s There seems to be a steady ~1 second difference in favor of the virtual version. Why is this? Relevant or not: dual-core pentium @ 2.80Ghz, no extra applications running between two tests. Archlinux with gcc 4.5.0. Compiling normally, like: $ g++ test.cpp -o normal Also, -Wall doesn't spit out any warnings, either.

    Read the article

  • Proper way to set object instance variables

    - by ensnare
    I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean: class User(object): def setName(self,name): #Do sanity checks on name self._name = name def setPassword(self,password): #Check password length > 6 characters #Encrypt to md5 self._password = password def commit(self): #Commit to database >>u = User() >>u.setName('Jason Martinez') >>u.setPassword('linebreak') >>u.commit() Is this the right approach? Should I declare class variables up top? Should I use a _ in front of all the class variables to make them private? Thanks for helping out.

    Read the article

  • C#: Inheritance, Overriding, and Hiding

    - by Rosarch
    I'm having difficulty with an architectural decision for my C# XNA game. The basic entity in the world, such as a tree, zombie, or the player, is represented as a GameObject. Each GameObject is composed of at least a GameObjectController, GameObjectModel, and GameObjectView. These three are enough for simple entities, like inanimate trees or rocks. However, as I try to keep the functionality as factored out as possible, the inheritance begins to feel unwieldy. Syntactically, I'm not even sure how best to accomplish my goals. Here is the GameObjectController: public class GameObjectController { protected GameObjectModel model; protected GameObjectView view; public GameObjectController(GameObjectManager gameObjectManager) { this.gameObjectManager = gameObjectManager; model = new GameObjectModel(this); view = new GameObjectView(this); } public GameObjectManager GameObjectManager { get { return gameObjectManager; } } public virtual GameObjectView View { get { return view; } } public virtual GameObjectModel Model { get { return model; } } public virtual void Update(long tick) { } } I want to specify that each subclass of GameObjectController will have accessible at least a GameObjectView and GameObjectModel. If subclasses are fine using those classes, but perhaps are overriding for a more sophisticated Update() method, I don't want them to have to duplicate the code to produce those dependencies. So, the GameObjectController constructor sets those objects up. However, some objects do want to override the model and view. This is where the trouble comes in. Some objects need to fight, so they are CombatantGameObjects: public class CombatantGameObject : GameObjectController { protected new readonly CombatantGameModel model; public new virtual CombatantGameModel Model { get { return model; } } protected readonly CombatEngine combatEngine; public CombatantGameObject(GameObjectManager gameObjectManager, CombatEngine combatEngine) : base(gameObjectManager) { model = new CombatantGameModel(this); this.combatEngine = combatEngine; } public override void Update(long tick) { if (model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); } base.Update(tick); } } Still pretty simple. Is my use of new to hide instance variables correct? Note that I'm assigning CombatantObjectController.model here, even though GameObjectController.Model was already set. And, combatants don't need any special view functionality, so they leave GameObjectController.View alone. Then I get down to the PlayerController, at which a bug is found. public class PlayerController : CombatantGameObject { private readonly IInputReader inputReader; private new readonly PlayerModel model; public new PlayerModel Model { get { return model; } } private float lastInventoryIndexAt; private float lastThrowAt; public PlayerController(GameObjectManager gameObjectManager, IInputReader inputReader, CombatEngine combatEngine) : base(gameObjectManager, combatEngine) { this.inputReader = inputReader; model = new PlayerModel(this); Model.Health = Constants.PLAYER_HEALTH; } public override void Update(long tick) { if (Model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); for (int i = 0; i < 10; i++) { Debug.WriteLine("YOU DEAD SON!!!"); } return; } UpdateFromInput(tick); // .... } } The first time that this line is executed, I get a null reference exception: model.Body.ApplyImpulse(movementImpulse, model.Position); model.Position looks at model.Body, which is null. This is a function that initializes GameObjects before they are deployed into the world: public void Initialize(GameObjectController controller, IDictionary<string, string> data, WorldState worldState) { controller.View.read(data); controller.View.createSpriteAnimations(data, _assets); controller.Model.read(data); SetUpPhysics(controller, worldState, controller.Model.BoundingCircleRadius, Single.Parse(data["x"]), Single.Parse(data["y"]), bool.Parse(data["isBullet"])); } Every object is passed as a GameObjectController. Does that mean that if the object is really a PlayerController, controller.Model will refer to the base's GameObjectModel and not the PlayerController's overriden PlayerObjectModel? In response to rh: This means that now for a PlayerModel p, p.Model is not equivalent to ((CombatantGameObject)p).Model, and also not equivalent to ((GameObjectController)p).Model. That is exactly what I do not want. I want: PlayerController p; p.Model == ((CombatantGameObject)p).Model p.Model == ((GameObjectController)p).Model How can I do this? override?

    Read the article

  • How do I dynamically instantiate a class in javascript?

    - by Adam
    I'm starting out with classes in Javascript and have hit a wall. I've looked all over for a tutorial that goes a little further than simply how to construct a class (usually Animal) then extend the class and have a Method do something (Dog alert('Bark');). I have created a class that I want a user to be able to instantiate (is that the right word)? For example the first stage in my program is for the user to give the class a name, and then start to populate the various variables in the class. When they've done that they may do it again many times. So if: var className = new MyObject(); How do I dynamically create the name of the new object className and then refer to it later in the code?

    Read the article

  • DDD and MVC: Difference between 'Model' and 'Entity'

    - by Nathan Loding
    I'm seriously confused about the concept of the 'Model' in MVC. Most frameworks that exist today put the Model between the Controller and the database, and the Model almost acts like a database abstraction layer. The concept of 'Fat Model Skinny Controller' is lost as the Controller starts doing more and more logic. In DDD, there is also the concept of a Domain Entity, which has a unique identity to it. As I understand it, a user is a good example of an Entity (unique userid, for instance). The Entity has a life-cycle -- it's values can change throughout the course of the action -- and then it's saved or discarded. The Entity I describe above is what I thought Model was supposed to be in MVC? How off-base am I? To clutter things more, you throw in other patterns, such as the Repository pattern (maybe putting a Service in there). It's pretty clear how the Repository would interact with an Entity -- how does it with a Model? Controllers can have multiple Models, which makes it seem like a Model is less a "database table" than it is a unique Entity. So, in very rough terms, which is better? No "Model" really ... class MyController { public function index() { $repo = new PostRepository(); $posts = $repo->findAllByDateRange('within 30 days'); foreach($posts as $post) { echo $post->Author; } } } Or this, which has a Model as the DAO? class MyController { public function index() { $model = new PostModel(); // maybe this returns a PostRepository? $posts = $model->findAllByDateRange('within 30 days'); while($posts->getNext()) { echo $posts->Post->Author; } } } Both those examples didn't even do what I was describing above. I'm clearly lost. Any input?

    Read the article

  • Best Practice for Utilities Class?

    - by Sonny Boy
    Hey all, We currently have a utilities class that handles a lot of string formatting, date displays, and similar functionality and it's a shared/static class. Is this the "correct" way of doing things or should we be instanciating the utility class as and when we need it? Our main goal here is to reduce memory footprint but performance of the application is also a consideration. Thanks, Matt PS. We're using .NET 2.0

    Read the article

  • JavaScript check if anonymous object has a method

    - by Baddie
    How can I check if an anonymous object that was created as such: var myObj = { prop1: 'no', prop2: function () { return false; } } does indeed have a prop2 defined? prop2 will always be defined as a function, but for some objects it is not required and will not be defined. I tried what was suggested here: http://stackoverflow.com/questions/595766/how-to-determine-if-native-javascript-object-has-a-property-method but I don't think it works for anonymous objects .

    Read the article

  • Where should Nhibernate IPostInsertEventListener go in the 3 tier architecture

    - by Quintin Par
    I have a IPostInsertEventListener implementation like public class NHibernateEventListener : IPostInsertEventListener, IPostUpdateEventListener which catches some entity inserts and does an additional insert to another table for ETL. Essentially it requires references to the Nhibernate, Domain entity and Repository<> Now where do I go about adding this class? If I add it to ApplicationServices I’ll end up referencing Nhibernate at that layer. If I add this to the Data layer, I’ll have to reference Domain (circular). How do I go implementing this class with S#arp principles? Any thoughts?

    Read the article

  • Can you declare <canvas> methods within a template in javascript?

    - by Binarytales
    Not entirely sure I posed the question in the best way but here goes... I have been playing around with the HTML5 canvas API and have got as far as drawing a shape in the canvas and getting it to move around with the arrow keys. I then tried to move my various variables and functions to a template so I could spawn multiple shapes (that would eventually be controlled by different keys). This is what I have: function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; this.playerSize = z; this.colour = colour; } playerOne = new player(100, 100, 10, "#F0F"); function persona(z, colour){ zone.fillStyle = colour; offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } function move(x, y){ playerOne.lx = playerOne.lx + x; playerOne.ly = playerOne.ly + y; zone.clearRect(0, 0, 500, 500); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); } window.onkeydown = function() { var direction = this.event.keyCode; var s = playerOne.speed; // Arrow Keys if( direction == 38 && playerOne.ly >= 10){ // Up move(0,-s); } if( direction == 40 && playerOne.ly <= 490){ // Down move(0,s); } if( direction == 37 && playerOne.lx >= 10){ // Left move(-s,0); } if( direction == 39 && playerOne.lx <= 490){ // Right move(s,0); } }; window.onload = function() { zone = document.getElementById('canvas').getContext('2d'); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); }; So what I tried to do was move the persona function into the player template like this: function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; function persona(){ zone.fillStyle = colour; var offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } } And then where before it said persona(playerOne.playerSize, playerOne.colour); it now just says playerOne.persona(); But this is just totally flaking out and not working and I can't figure out why. I'm probably going about it all the wrong way and I think the problem is that I'm trying to manipulate the canvas.context (call zone in my script) from within a object/template. Perhaps its nothing to do with that at all and I an just not declaring my persona functions properly in the context of the template. Documentation for the canvas API is very thin on the ground and any hint in the right direction will be very much appreciated.

    Read the article

  • Implementation question involving implementing an interface

    - by Vivin Paliath
    I'm writing a set of collection classes for different types of Trees. I'm doing this as a learning exercise and I'm also hoping it turns out to be something useful. I really want to do this the right way and so I've been reading Effective Java and I've also been looking at the way Joshua Bloch implemented the collection classes by looking at the source. I seem to have a fair idea of what is being done, but I still have a few things to sort out. I have a Node<T> interface and an AbstractNode<T> class that implements the Node interface. I then created a GenericNode<T> (a node that can have 0 to n children, and that is part of an n-ary tree) class that extends AbstractNode<T> and implements Node<T>. This part was easy. Next, I created a Tree<T> interface and an AbstractTree<T> class that implements the Tree<T> interface. After that, I started writing a GenericTree<T> class that extends AbstractTree<T> and implements Tree<T>. This is where I started having problems. As far as the design is concerned, a GenericTree<T> can only consist of nodes of type GenericTreeNode<T>. This includes the root. In my Tree<T> interface I have: public interface Tree<T> { void setRoot(Node<T> root); Node<T> getRoot(); List<Node<T>> postOrder(); ... rest omitted ... } And, AbstractTree<T> implements this interface: public abstract class AbstractTree<T> implements Tree<T> { protected Node<T> root; protected AbstractTree() { } protected AbstractTree(Node<T> root) { this.root = root; } public void setRoot(Node<T> root) { this.root = root; } public Node<T> getRoot() { return this.root; } ... rest omitted ... } In GenericTree<T>, I can have: public GenericTree(Node<T> root) { super(root); } But what this means is that you can create a generic tree using any subtype of Node<T>. You can also set the root of a tree to any subtype of Node<T>. I want to be able to restrict the type of the node to the type of the tree that it can represent. To fix this, I can do this: public GenericTree(GenericNode<T> root) { super(root); } However, setRoot still accepts a parameter of type Node<T>. Which means a user can still create a tree with the wrong type of root node. How do I enforce this constraint? The only way I can think of doing is either: Do an instanceof which limits the check to runtime. I'm not a huge fan of this. Remove setRoot from the interface and have the base class implement this method. This means that it is not part of the contract and anyone who wants to make a new type of tree needs to remember to implement this method. Is there a better way? The second question I have concerns the return type of postOrder which is List<Node<T>>. This means that if a user is operating on a GenericTree<T> object and calls postOrder, he or she receives a list that consists of Node<T> objects. This means when iterating through (using a foreach construct) they would have perform an explicit cast to GenericNode<T> if they want to use methods that are only defined in that class. I don't like having to place this burden on the user. What are my options in this case? I can only think of removing the method from the interface and have the subclass implement this method making sure that it returns a list of appropriate subtype of Node<T>. However, this once again removes it from the contract and it's anyone who wants to create a new type of tree has to remember to implement this method. Is there a better way?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >